Index: /tags/Mars_V0-8-4/MagicSoft/Mars/.rootrc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/.rootrc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/.rootrc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Changelog
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog	(revision 3781)
@@ -0,0 +1,4554 @@
+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/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ópez
+
+   * 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 L¢pez
+
+   * 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-8-4/MagicSoft/Mars/Changelog.02
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog.02	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog.02	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Changelog.03
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog.03	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Changelog.03	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/MIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/MIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/MIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/MLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/MLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/MLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile	(revision 3781)
@@ -0,0 +1,152 @@
+##################################################################
+#
+#   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 readraw merpp star status mars mona
+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 \
+	  mcalib \
+          mfileio \
+          mreflector \
+          mgeom \
+          msql \
+          mimage \
+          mmontecarlo \
+          mmc \
+          mraw \
+          mcamera \
+          mpointing \
+          mreport \
+          mgui \
+          mranforest \
+          mhistmc \
+          mjobs \
+          mtools
+
+#          monline \
+
+#LIBRARIES = $(SUBDIRS:%=lib/lib%.a)
+LIBRARIES = $(SUBDIRS:=.a)
+MRPROPERS = $(SUBDIRS:=.mrproper)
+CLEANERS  = $(SUBDIRS:=.clean)
+LIBS      = $(SOLIB)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .h .o 
+
+SRCFILES =
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) MCint.o
+
+############################################################
+all: rmlib $(SOLIB) $(PROGRAMS)
+	@echo " Done. "
+	@echo " "
+
+static: LIBS=$(SUBDIRS:=/*.o) $(OBJS)
+static: rmlib $(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 $(SOLIB) ..."
+	$(CXX) $(CXXFLAGS) $(DYNLIB) $(OBJS) $(SUBDIRS:=/*.o) $(ROOTGLIBS) -o $@
+#	$(CXX) $(CXXFLAGS) $(DYNLIB) $(OBJS) -Wl,--export-dynamic -Llib $(LIBRARIES:%.a=-l%) -o $@
+
+$(PROGRAMS): $(LIBS) $(PROGRAMS:=.o)
+	@echo " Linking $@ ..." 
+	$(CXX) $(CXXFLAGS) $(ROOTGLIBS) $(LIBS) $@.o $(MARS_LIB) -o $@
+
+# FOR CONVINIENCE CREATE Dep-file first!
+$(LIBRARIES):
+	@echo " Creating lib$@:"
+	(cd $*; $(MAKE) -f Makefile; cd ..; mv $*/$@ lib/lib$@)
+
+$(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 ..;) 
+
+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-8-4/MagicSoft/Mars/Makefile.conf.darwin
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.darwin	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.darwin	(revision 3781)
@@ -0,0 +1,42 @@
+##################################################################
+#
+# 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__
+DYNLIB   = -dynamiclib
+
+# 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-8-4/MagicSoft/Mars/Makefile.conf.general
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.general	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.general	(revision 3781)
@@ -0,0 +1,25 @@
+#
+#  ----->>>   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.8.4\" -D__MARS__ -DROOTVER=\"$(ROOTVER)\" $(ARCHDEF) $(MARSDEFINES)
+
+CXXFLAGS  = $(ROOTCFLAGS) $(INCLUDES) $(OPTIM) $(DEBUG) $(DEFINES)
+CFLAGS    = $(CXXFLAGS) $(MARSFLAGS)
+FFLAGS    = $(CXXFLAGS)
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux	(revision 3781)
@@ -0,0 +1,42 @@
+##################################################################
+#
+# config.mk
+#
+# @file        config.mk
+# 
+##################################################################
+# @maintitle
+
+# @code
+
+# 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__
+DYNLIB   = -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:
+
+# @endcode
+##EOF
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux-gnu
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux-gnu	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.linux-gnu	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Makefile.conf.osf1
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.osf1	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.osf1	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Makefile.conf.osf5.1
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.osf5.1	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.conf.osf5.1	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/Makefile.rules
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.rules	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/Makefile.rules	(revision 3781)
@@ -0,0 +1,81 @@
+include $(CINT)Dep.d
+
+$(LIB): $(OBJS) $(CINT)Cint.o
+	@echo " - Building Library lib$(LIB)"
+	$(AR) $(LIB) $(OBJS) $(CINT)Cint.o
+	@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) 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) 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-8-4/MagicSoft/Mars/NEWS
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/NEWS	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/NEWS	(revision 3781)
@@ -0,0 +1,572 @@
+                                                               -*-*- END -*-*-
+ *** Version 0.8.4 (2004/04/19)
+
+   - 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-8-4/MagicSoft/Mars/lib/lib.txt
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/lib/lib.txt	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/lib/lib.txt	(revision 3781)
@@ -0,0 +1,1 @@
+Directory for libraries while compiling
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CCDataCheck.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CCDataCheck.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CCDataCheck.C	(revision 3781)
@@ -0,0 +1,1354 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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_02_11.root", const TString directory="../")
+{
+
+  //
+  // Check of the raw files
+  //
+//    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);
+//    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;
+  TAxis *axey;
+  TAxis *axex;
+  MH3 *mh3;
+  MHPixVsTime *pixclone1;
+  MHCamera *Sum;
+  //
+  // Drive report (pointing.C from T. Bretz)
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c1 = d.AddTab("DRIVE SYSTEM");
+  else
+    TCanvas *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);
+  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->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()->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()->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");
+      axey->SetLabelSize(0.05);
+      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");
+      axey->SetLabelSize(0.05);
+      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->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");
+      axey->SetLabelSize(0.05);
+      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->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");
+      axey->SetLabelSize(0.09);
+      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]");
+    }
+  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 [%]");
+    }
+  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->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("");
+      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->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");
+      axey->SetLabelSize(0.05);
+      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->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->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->GetXaxis()->SetLabelSize(0.05);
+      hist->GetYaxis()->SetLabelSize(0.05);
+      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->GetXaxis()->SetLabelSize(0.05);
+   hist->GetYaxis()->SetLabelSize(0.05);
+   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");
+       axey->SetLabelSize(0.05);
+       hist->GetXaxis()->SetLabelSize(0.05);
+       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.70,0.80,0.99,0.99);
+  g = htrigmc1.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  legtrig->AddEntry(g,Form("Macrocell 1: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of mc 1 : (maximum)");
+  pixclone1 = (MHPixVsTime*)htrigmc1.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]");
+    }
+  legtrig->DrawClone();
+  c8->cd(2);
+  gPad->SetLogy();
+  TLegend *legtrig = new TLegend(0.70,0.70,0.99,0.99);
+  g = htrigmc2.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  legtrig->AddEntry(g,Form("Macrocell 2: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of mc 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]");
+    }
+  g=htrigmc3.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  legtrig->AddEntry(g,Form("Macrocell 3: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+    hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  pixclone1 = (MHPixVsTime*)htrigmc3.DrawClone("nonewsame");
+  g=htrigmc4.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(4);
+  legtrig->AddEntry(g,Form("Macrocell 4: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  if(hist->GetMaximum()<g->GetHistogram()->GetMaximum())
+    hist->SetMaximum(g->GetHistogram()->GetMaximum());
+  pixclone1 = (MHPixVsTime*)htrigmc4.DrawClone("nonewsame");
+  g=htrigmc5.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(5);
+  legtrig->AddEntry(g,Form("Macrocell 5: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 6: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 7: %3.0f",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.70,0.70,0.99,0.99);
+  g = htrigmc8.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  legtrig->AddEntry(g,Form("Macrocell 8: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of mc 8-13 : (maximum)");
+  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]");
+    }
+  g=htrigmc9.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  legtrig->AddEntry(g,Form("Macrocell 9: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 10: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 11: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 12: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  pixclone1 = (MHPixVsTime*)htrigmc12.DrawClone("nonewsame");
+  g=htrigmc13.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(7);
+  legtrig->AddEntry(g,Form("Macrocell 13: %3.0f",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.70,0.70,0.99,0.99);
+  TGraph *g = htrigmc14.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(2);
+  legtrig->AddEntry(g,Form("Macrocell 14: %3.0f",g->GetHistogram()->GetMaximum()),"p");
+  g->SetTitle("Trigger rate of mc 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]");
+    }
+  g=htrigmc15.GetGraph();
+  g->SetMarkerStyle(kFullDotSmall);
+  g->SetMarkerColor(3);
+  legtrig->AddEntry(g,Form("Macrocell 15: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 16: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 17: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 18: %3.0f",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);
+  legtrig->AddEntry(g,Form("Macrocell 19: %3.0f",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-8-4/MagicSoft/Mars/macros/CT1Analysis.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1Analysis.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1Analysis.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/CT1EgyEst.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1EgyEst.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1EgyEst.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/CT1Hillas.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1Hillas.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1Hillas.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/CT1collarea.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1collarea.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1collarea.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/CT1env.rc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1env.rc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/CT1env.rc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/DAQDataCheck.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/DAQDataCheck.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/DAQDataCheck.C	(revision 3781)
@@ -0,0 +1,668 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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, 03/2004 <mailto:reyes@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== *//////////////////////////////////////////////////////////////////////////////
+//
+// This macro made the check of the DAQ files (.raw files).
+//
+// WARNING!: This macro only works if the directory is alphabetically ordered
+//
+///////////////////////////////////////////////////////////////////////////
+#include "MAGIC.h"
+
+void DataAnalysis(const MReadMarsFile *pedfiles,const MReadMarsFile *calfiles,const MReadMarsFile *datafiles,TString directory="./")
+{
+
+  TVirtualPad *c;
+
+  Bool_t batchmode = kTRUE;
+
+  if(!batchmode)
+    {
+      MStatusDisplay *d = new MStatusDisplay;
+      d->SetLogStream(&gLog, kTRUE);            // Disables output to stdout  
+    }
+
+  // 
+  // Set up the source run-range
+  //
+  TRegexp run("_[0-9][0-9][0-9][0-9][0-9]_");
+  TRegexp type("_[A-Z]_");
+  TString ped = "", cal = "", data = "", source = "";
+  if(pedfiles->GetEntries()!=0)
+    source = pedfiles->GetFileName();
+  else if(calfiles->GetEntries()!=0)
+    source = calfiles->GetFileName();
+  else
+    source = datafiles->GetFileName();
+
+  ped = pedfiles->GetFileName();
+  if(calfiles->GetEntries()!=0)
+    cal = calfiles->GetFileName();
+  if(datafiles->GetEntries()!=0)
+    data = datafiles->GetFileName();
+  
+  ped = ped(ped.Index(run)+1,5);
+  cal = cal(cal.Index(run)+1,5);
+  data = data(data.Index(run)+1,5);
+
+  source = source(source.Index(type)+3,source.Length());
+  source.Remove(source.Last('_'),source.Length());
+
+//    cout << ped << endl;
+//    cout << cal << endl;
+//    cout << data << endl;
+//    cout << source << endl;
+
+  // **********************************************************************
+  // ***************************** PEDESTALS ******************************
+  // **********************************************************************
+  if(pedfiles->GetEntries()==0)
+    {
+      cout << "Warning, no entries found in pedestal run(s)!!!"<< endl;
+      break;
+    }
+  MParList plist;
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+  
+//    pedfiles->Print("all");
+  //
+  // Now setup the tasks and tasklist for the pedestals:
+  // ---------------------------------------------------
+  //
+  
+  //tasks
+  pedfiles->DisableAutoScheme();
+  tlist.AddToList(pedfiles);
+  
+  // pedestal tasks and containers
+  MGeomCamMagic  geomcam;
+  plist.AddToList(&geomcam);
+  MPedestalCam   pedcam;
+  plist.AddToList(&pedcam);
+  
+  MGeomApply geomapl;
+  tlist.AddToList(&geomapl);
+  MPedCalcPedRun pedcalc;
+  tlist.AddToList(&pedcalc);
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop;
+  evtloop.SetParList(&plist);
+  if(!batchmode)
+    evtloop.SetDisplay(d);
+  
+  //
+  // Execute first analysis
+  //
+  cout << "*************************" << endl;
+  cout << "** COMPUTING PEDESTALS **" << endl;
+  cout << "*************************" << endl;
+  if (!evtloop.Eventloop())
+    return;
+  
+  tlist.PrintStatistics();
+  
+  //
+  // Display the pedestal checking plots
+  //
+  if ((d = evtloop.GetDisplay()))
+    TCanvas &c1 = d.AddTab("PEDESTALS");
+  else
+    TCanvas *c1 = new TCanvas();
+  MHCamera meanped(geomcam,"MPedestalCam;ped","Pedestals");
+  meanped.SetCamContent(pedcam, 0);
+  meanped.SetCamError(pedcam, 1);
+  MHCamera rmsped(geomcam,"MPedestalCam;var","Sigma Pedestal");
+  rmsped.SetCamContent(pedcam, 2);
+  c1->Divide(1,2);
+  gPad->SetBorderMode(0);
+  c1->cd(1);
+  meanped.DrawClone("nonewEPhist");
+  c1->cd(2);
+  gPad->SetBorderMode(0);
+  c = gPad;
+  c->Divide(2,1);
+  c->cd(1);
+  meanped.DrawClone("nonewpixelindex");
+  c->cd(2);
+  rmsped.DrawClone("nonewpixelindex");
+
+  //
+  // Save canvas/display into a postcript file
+  //
+
+  if ((d = evtloop.GetDisplay()))
+    d->SaveAsPS(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+  else
+    c1->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps(");
+
+  if(calfiles->GetEntries()==0)
+    c1->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps]");
+
+  // **********************************************************************
+  // ***************************** CALIBRATION ****************************
+  // **********************************************************************
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  if(calfiles->GetEntries()==0)
+    {
+      cout << "Warning, no entries found in calibration run(s)!!!"<< endl;
+      break;
+    }
+  MParList  plist2;
+  MTaskList tlist2;
+  plist2.AddToList(&tlist2);
+  
+//    calfiles->Print("all");
+  //
+  // Now setup the new tasks and tasklist for the calibration
+  // ---------------------------------------------------
+  //
+  
+  calfiles->DisableAutoScheme();
+  tlist2.AddToList(calfiles);  
+  
+  MExtractedSignalCam        sigcam;
+  MArrivalTimeCam            timecam;
+  MBadPixelsCam              badcam;
+  MCalibrationChargeCam      calcam;
+  MCalibrationChargePINDiode pindiode;
+  MCalibrationChargeBlindPix blindpix;
+  
+  MHCalibrationRelTimeCam     histtime;
+  MHCalibrationChargeCam      histcharge;
+  MHCalibrationChargePINDiode histpin;
+  MHCalibrationChargeBlindPix histblind;
+  //
+  // As long, as we don't have digital modules,
+  // we have to set the color of the pulser LED by hand
+  //
+  blindpix.SetColor(kCT1);
+  pindiode.SetColor(kCT1);
+  //
+  // Get the previously created MPedestalCam and MGeomCamMagic 
+  // into the new Parameter List
+  //
+  plist2.AddToList(&pedcam);
+  plist2.AddToList(&geomcam);
+
+  plist2.AddToList(&sigcam);
+  plist2.AddToList(&timecam);
+  plist2.AddToList(&badcam);
+  plist2.AddToList(&calcam);
+  plist2.AddToList(&histtime);
+  plist2.AddToList(&histcharge);
+  plist2.AddToList(&histpin);
+  plist2.AddToList(&histblind);
+  
+  //
+  // We saw that the signal jumps between slices,
+  // thus take the sliding window
+  //
+  MExtractSignal2        sigcalc2;
+  MExtractPINDiode       pincalc;
+  MExtractBlindPixel     blindcalc;
+  MArrivalTimeCalc2      timecalc;
+  MCalibrationChargeCalc calcalc;
+  
+  MFillH filltime( "MHCalibrationRelTimeCam"    , "MArrivalTimeCam");
+  MFillH fillpin  ("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode"); 
+  MFillH fillblind("MHCalibrationChargeBlindPix", "MExtractedSignalBlindPixel");
+  MFillH fillcam  ("MHCalibrationChargeCam"     , "MExtractedSignalCam");
+  
+  // Skip the MFillH draw function
+  filltime.SetBit(MFillH::kDoNotDisplay);
+  fillpin.SetBit(MFillH::kDoNotDisplay);
+  fillblind.SetBit(MFillH::kDoNotDisplay);
+  fillcam.SetBit(MFillH::kDoNotDisplay);
+  
+  //
+  // Skip the HiGain vs. LoGain calibration
+  //
+  calcalc.SkipHiLoGainCalibration();
+  
+  //
+  // Apply a filter against cosmics
+  // (was directly in MCalibrationCalc in earlier versions)
+  //
+  MFCosmics            cosmics;
+  MContinue            cont(&cosmics);
+  //
+  // Get the previously created MGeomApply into the new Task List
+  //  
+  tlist2.AddToList(&geomapl);
+
+  tlist2.AddToList(&sigcalc2);
+  tlist2.AddToList(&pincalc);
+  tlist2.AddToList(&blindcalc);
+  //
+  // 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
+  //
+  tlist2.AddToList(&timecalc);
+  tlist2.AddToList(&filltime);
+
+  tlist2.AddToList(&fillpin);
+  tlist2.AddToList(&fillblind);
+  tlist2.AddToList(&fillcam);
+  tlist2.AddToList(&calcalc);
+  
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop2;
+  evtloop2.SetParList(&plist2);
+  if(!batchmode)
+    evtloop2.SetDisplay(d);
+  
+  //
+  // Execute second analysis
+  //
+  cout << "***********************************" << endl;
+  cout << "** COMPUTING CALIBRATION FACTORS **" << endl;
+  cout << "***********************************" << endl;
+  if (!evtloop2.Eventloop())
+    return;
+  
+  tlist2.PrintStatistics();
+  
+  //
+  // print the most important results of all pixels to a file
+  //
+  //    MLog gauglog;
+  //    gauglog.SetOutputFile(Form("%s%s",calcam.GetName(),".txt"),1);
+  //    calcam.SetLogStream(&gauglog);
+  //    calcam.Print();
+  //    calcam.SetLogStream(&gLog);
+
+  TH1 *hist;
+
+  //
+  // Display the calibration checking plots
+  //      
+  // ---------------------- Conversion factor ---------------------------
+  if ((d = evtloop2.GetDisplay()))
+    TCanvas &c2 = d.AddTab("CONV FACTOR");
+  else
+    TCanvas *c2 = new TCanvas();
+  c2->Divide(1,2);
+  c2->cd(1);
+  gPad->SetBorderMode(0);
+  c = gPad;
+  c->Divide(2,1);
+  gPad->SetBorderMode(0);
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  MHCamera ConvFfactor(geomcam,"Cal;FFactorConv","Conversion Factor to photons (F-Factor method)");
+  ConvFfactor.SetCamContent(calcam, 11);
+  ConvFfactor.DrawClone("nonewpixelindex");
+  c->cd(2);
+  MHCamera ConvBlindPix(geomcam,"Cal;BlindPixConv","Conversion Factor to photons (Blind Pixel method)");
+  ConvBlindPix.SetCamContent(calcam, 17);
+  ConvBlindPix.DrawClone("nonewpixelindex");
+  c2->cd(2);
+  gPad->SetBorderMode(0);
+  MHCamera ConvPINDiode(geomcam,"Cal;PINDiodeConv","Conversion Factor to photons (PINDiode method)");
+  ConvPINDiode.SetCamContent(calcam, 23);
+  ConvPINDiode.DrawClone("nonewpixelindex");
+  // ----------------- Pixels with defects ------------------------------
+  if ((d = evtloop2.GetDisplay()))
+    TCanvas &c3 = d.AddTab("DEFECT PIXELS");
+  else
+    TCanvas *c3 = new TCanvas();
+  c3->Divide(3,2);
+  c3->cd(1);
+  MHCamera PixExc(geomcam,"Cal;Excluded","Pixels previously excluded");
+  PixExc.SetCamContent(calcam, 27);
+  PixExc.DrawClone("nonewpixelindex");
+  c3->cd(2);
+  MHCamera PixNoFit(geomcam,"Cal;NotFitted","Pixels that could not be fitted");
+  PixNoFit.SetCamContent(calcam, 28);
+  PixNoFit.DrawClone("nonewpixelindex");
+  c3->cd(3);
+  MHCamera PixNoValid(geomcam,"Cal;NotValidFit","Pixels with not valid fit results");
+  PixNoValid.SetCamContent(calcam, 29);
+  PixNoValid.DrawClone("nonewpixelindex");
+  c3->cd(4);
+  MHCamera PixFFactor(geomcam,"Cal;FFactorValid","Pixels with valid F-Factor calibration");
+  PixFFactor.SetCamContent(calcam, 35);
+  PixFFactor.DrawClone("nonewpixelindex");
+  c3->cd(5);
+  MHCamera PixBlind(geomcam,"Cal;BlindPixelValid","Pixels with valid BlindPixel calibration");
+  PixBlind.SetCamContent(calcam, 36);
+  PixBlind.DrawClone("nonewpixelindex");
+  c3->cd(6);
+  MHCamera PixPINDiode(geomcam,"Cal;PINdiodeFFactorValid","Pixels with valid PINDiode calibration");
+  PixPINDiode.SetCamContent(calcam, 37);
+  PixPINDiode.DrawClone("nonewpixelindex");
+  // ------------------------- Fitted mean charges ----------------------------
+  if ((d = evtloop2.GetDisplay()))
+    TCanvas &c4 = d.AddTab("FIT CHARGES");
+  else
+    TCanvas *c4 = new TCanvas();
+  c4->Divide(1,2);
+  MHCamera fitmeancharge(geomcam,"Cal;Charge","Fitted Mean Charges");
+  fitmeancharge.SetCamContent(calcam, 0);
+  fitmeancharge.SetCamError(calcam, 1);
+  c4->cd(1);
+  gPad->SetBorderMode(0);
+  fitmeancharge.DrawClone("nonewEPhist");
+  c4->cd(2);
+  c = gPad;
+  gPad->SetBorderMode(0);
+  c->Divide(2,1);
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  fitmeancharge.DrawClone("nonewpixelindex");
+  c->cd(2);
+  gPad->SetBorderMode(0);
+  hist = (TH1*)fitmeancharge->Projection("Charge");
+  hist->SetXTitle("Charge");
+  hist->DrawCopy("hist");
+  // ----------------------- Reduced Sigma per Charge -------------------------
+  if ((d = evtloop2.GetDisplay()))
+    TCanvas &c5 = d.AddTab("RED SIGMA");
+  else
+    TCanvas *c5 = new TCanvas();
+  c5->Divide(1,2);
+  MHCamera redsigmacharge(geomcam,"Cal;RSigmaCharge","Reduced Sigma per Charge");
+  redsigmacharge.SetCamContent(calcam, 7);
+  redsigmacharge.SetCamError(calcam, 8);
+  c5->cd(1);
+  gPad->SetBorderMode(0);
+  redsigmacharge.DrawClone("nonewEPhist");
+  c5->cd(2);
+  c = gPad;
+  gPad->SetBorderMode(0);
+  c->Divide(2,1);
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  redsigmacharge.DrawClone("nonewpixelindex");
+  c->cd(2);
+  gPad->SetBorderMode(0);
+  hist = redsigmacharge->Projection("RSigmaCharge");
+  hist->SetXTitle("Reduced Sigma per Charge");
+  hist->Draw("hist");
+  // ----------------------- Absolute arrival times -------------------------
+  if ((d = evtloop2.GetDisplay()))
+    TCanvas &c6 = d.AddTab("ABS TIMES");
+  else
+    TCanvas *c6 = new TCanvas();
+  c6->Divide(1,2);
+  MHCamera abstime(geomcam,"Cal;AbsTimeMean","Absolute Arrival Times");
+  abstime.SetCamContent(calcam, 42);
+  abstime.SetCamError(calcam, 43);
+  c6->cd(1);
+  gPad->SetBorderMode(0);
+  abstime.DrawClone("nonewEPhist");
+  c6->cd(2);
+  c = gPad;
+  gPad->SetBorderMode(0);
+  c->Divide(2,1);
+  c->cd(1);
+  gPad->SetBorderMode(0);
+  abstime.DrawClone("nonewpixelindex");
+  c->cd(2);
+  gPad->SetBorderMode(0);
+  hist = (TH1*)abstime->Projection("AbsTimeMean");
+  hist->SetXTitle("Absolute arrival time (time slice)");
+  hist->DrawCopy("hist");
+
+  //
+  // Save canvas/display into a postcript file
+  //
+
+  if ((d = evtloop2.GetDisplay()))
+    d->SaveAsPS(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+  else
+    {
+      c2->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+      c3->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+      c4->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+      c5->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+      c6->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+    }
+
+  if(calfiles->GetEntries()!=0)
+    c6->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps]");
+
+  // ********************************************************************
+  // ***************************** DATA *********************************
+  // ********************************************************************
+
+  if(datafiles->GetEntries()==0)
+    {
+      cout << "Warning, no entries found in data run(s)!!!"<< endl;
+      break;
+    }
+  //
+  // Create an empty Parameter List and an empty Task List
+  //
+  MParList  plist3;
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+  
+//    datafiles->Print("all");
+  //
+  // Now setup the new tasks and tasklist for the data
+  // ---------------------------------------------------
+  //
+  
+  datafiles->DisableAutoScheme();
+  tlist3.AddToList(datafiles);  
+  
+  // Task containers
+  MExtractedSignalCam sigcam;
+  //
+  // Get the previously created MPedestalCam and MGeomCamMagic
+  // into the new Parameter List
+  //
+  plist3.AddToList(&geomcam);
+  plist3.AddToList(&pedcam);
+
+  plist3.AddToList(&sigcam);
+
+  // Display containers
+  MHTimeDiffTime difftime("DiffTime","Differential time between events");
+  plist3.AddToList(&difftime);
+  MBinning binsdifftime("BinningTimeDiff");
+  binsdifftime.SetEdges(200, 0., 0.2);
+  plist3.AddToList(&binsdifftime);
+  MBinning binstime("BinningTime");
+  binstime.SetEdges(10000, 0., 1e10);
+  plist3.AddToList(&binstime);
+
+  // Data tasks
+  MExtractSignal2 signal2;
+
+  MFillH fillDiffTime(&difftime,"MRawEvtData");
+  fillDiffTime.SetBit(MFillH::kDoNotDisplay);
+  tlist3.AddToList(&fillDiffTime);
+
+  //
+  // Get the previously created MGeomApply into the new Task List
+  //
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&signal2);
+
+  //
+  // Create and setup the eventloop
+  //
+  MEvtLoop evtloop3;
+  evtloop3.SetParList(&plist3);
+  if(!batchmode)
+    evtloop3.SetDisplay(d);
+  
+  //
+  // Execute third analysis
+  //
+  cout << "********************" << endl;
+  cout << "** COMPUTING DATA **" << endl;
+  cout << "********************" << endl;
+  if (!evtloop3.Eventloop())
+    return;
+  
+  tlist3.PrintStatistics();
+
+  TH1 *hist1;
+  TH2 *hist2;
+
+  //
+  // Display the data checking canvas
+  //
+  // -------------------- Diffential time of events ---------------------
+  if ((d = evtloop3.GetDisplay()))
+    TCanvas &c9 = d.AddTab("TIME");
+  else
+    TCanvas *c9 = new TCanvas();
+  gStyle->SetPadGridX(kTRUE);
+  gStyle->SetPadGridY(kTRUE);
+  gStyle->SetOptFit();
+  c9->Divide(2,2);
+  hist2 = difftime.GetHist();
+  c9->cd(1);
+  gPad->SetLogy();
+  hist1 = hist2->ProjectionX("ProjX_sumtime", -1, 9999, "E");  
+  hist1->SetTitle("Distribution of \\Delta t [s]");
+  hist1->SetXTitle("\\Delta t [s]");
+  hist1->SetYTitle("Counts");
+  hist1->GetXaxis()->SetRange(0,hist1->GetXaxis()->GetNbins());
+  TF1 *f1 = new TF1("f1","[0]*exp(x*[1])",hist1->GetMaximumBin(),hist1->GetXaxis()->GetXmax());
+  hist1->Fit(f1,"");
+  hist1->DrawCopy();
+  c9->cd(2);
+  gPad->SetLogy();
+  hist1 = hist2->ProjectionX("ProjX_sumtime", -1, 9999, "E");  
+  hist1->SetTitle("Distribution of \\Delta t [s] (deadtime)");
+  hist1->SetXTitle("\\Delta t [s]");
+  hist1->SetYTitle("Counts");
+//    cout << hist1->GetXaxis()->GetBinCenter(hist1->GetMaximumBin())<< endl;
+  hist1->GetXaxis()->SetRange(0,hist1->GetMaximumBin());
+  hist1->DrawCopy();
+  c9->cd(3);
+  hist1 = difftime.GetHist()->ProjectionY("ProjY_sumtime", -1, 9999, "E");  
+  hist1->SetTitle("Distribution of time [s]");
+  hist1->SetXTitle("Time t [s]");
+  hist1->SetYTitle("Counts");
+  hist1->DrawCopy();
+  c9->cd(4);
+
+  //
+  // Save canvas/display into a postcript file
+  //
+
+  if ((d = evtloop3.GetDisplay()))
+    d->SaveAsPS(directory+source+"_"+ped+"-"+cal+"-"+data+".ps");
+  else
+    {
+      c9->Print(directory+source+"_"+ped+"-"+cal+"-"+data+".ps)");
+    }
+  
+}
+
+void DAQDataCheck(const TString directory="/remote/data2/data/Magic-DATA/Period014/rootdata/2004_02_10/")
+{
+
+  MDirIter Next;
+  Next.AddDirectory(directory,"*_E.root",-1);
+
+//    Next.Print("all");
+
+  TString fName="file.root";
+
+  MReadMarsFile *pedfiles;
+  MReadMarsFile *calfiles;
+  MReadMarsFile *datafiles;
+
+  TString source="";
+
+  fName = Next();  // absolut path
+
+  while(!fName.IsNull())
+    {
+
+      TString file = fName(fName.Last('/')+1,fName.Length()); // root file name
+      file = file(0,file.Last('_'));
+
+//        TString run = file(file.First('_')+1,5);
+//        TString type = file(file.Index('_',file.First('_')+1)+1,1);
+      source = file(file.Last('_')+1,file.Length());
+
+      // Pedestal runs
+      if(fName.Contains("_P_"))
+	pedfiles = new MReadMarsFile("Events");
+      else
+	pedfiles->Rewind();
+
+      while(fName.Contains("_P_")&&fName.Contains(source))
+	{
+	  pedfiles->AddFile(fName);
+	  fName = Next();  
+	}
+
+      // Calibration runs
+      if(fName.Contains("_C_")||(!fName.Contains(source)))
+	calfiles = new MReadMarsFile("Events");
+      else
+	calfiles->Rewind();
+
+      while(fName.Contains("_C_")&&fName.Contains(source))
+	{
+	  calfiles->AddFile(fName);
+	  fName = Next();  
+	}
+
+      // Data runs
+      if(fName.Contains("_D_")||(!fName.Contains(source)))
+	datafiles = new MReadMarsFile("Events");
+//        else
+//  	break;
+      while(fName.Contains("_D_")&&fName.Contains(source))
+	{
+	  datafiles->AddFile(fName);
+	  fName = Next();  
+	}
+
+//        pedfiles->Print();
+//        calfiles->Print("all");
+//        datafiles->Print("all");
+
+      DataAnalysis(pedfiles,calfiles,datafiles,directory);
+
+      cout << "----------------------------------------------" << endl;
+
+    }
+
+}
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/MagicHillas.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/MagicHillas.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/MagicHillas.C	(revision 3781)
@@ -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 et al,  12/2000 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+
+void MagicHillas(const char *filename="~/data/Gamma_20_N*.root")
+{
+    //
+    // 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);
+
+    //
+    // 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();
+
+    MGeomApply geomapl;
+
+    MMcPedestalCopy pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    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);
+    //
+
+    MImgCleanStd    clean;
+    MBlindPixelCalc blind;
+    //
+    // Instead of unmapping the pixels you can also
+    //
+    // blind.SetUseInterpolation();
+    // blind.SetUseCetralPixel();
+    //
+    MHillasCalc    hcalc;
+    MHillasSrcCalc csrc1;
+
+    MFillH hfill1("MHHillas", "MHillas");
+    MFillH hfill2("MHHillasExt");
+    MFillH hfill3("MHStarMap", "MHillas");
+    MFillH hfill4("HistExtSource [MHHillasExt]", "MHillasSrc");
+    MFillH hfill5("HistSource [MHHillasSrc]", "MHillasSrc");
+    MFillH hfill6("MHNewImagePar");
+
+    MWriteRootFile write("hillas.root");
+    write.AddContainer("MHStarMap");
+    write.AddContainer("MHHillas");
+    write.AddContainer("MHHillasExt");
+    write.AddContainer("HistSource");
+    write.AddContainer("HistExtSource");
+    write.AddContainer("MHNewImagePar");
+
+    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-8-4/MagicSoft/Mars/macros/ONAnalysis.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONAnalysis.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONAnalysis.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/ONOFFAnalysis.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONOFFAnalysis.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONOFFAnalysis.C	(revision 3781)
@@ -0,0 +1,3634 @@
+
+//#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 *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, -300.0, 500.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 ONOFFAnalysis()
+{
+      gLog.SetNoColors();
+
+      if (gRandom)
+        delete gRandom;
+      gRandom = new TRandom3(0);
+
+      //-----------------------------------------------
+      //TString tag = "040126";
+      TString tag = "040127";
+      //TString tag = "040215";
+
+      //const char *offfile = "~magican/ct1test/wittek/offdata.preproc"; 
+      //const char *offfile = "20040126_OffCrab_"; 
+      //const char *offfile  = "*.OFF";
+      //const char *offfile  = "12776.OFF";
+      // 27 Jan 04
+      //const char *offfile  = "12*.OFF";
+      // 26 Jan 04
+      //const char *offfile  = "*.OFF";
+      // 15 Feb 04
+      const char *offfile  = "*.OFF";
+
+
+      //const char *onfile  = "~magican/ct1test/wittek/mkn421_on.preproc"; 
+      //      const char *onfile  = "~magican/ct1test/wittek/mkn421_00-01"; 
+      //const char *onfile  = "20040126_Crab_";
+      //const char *onfile  = "MCerPhot_output";
+      //const char *onfile  = "*.ON";
+      const char *onfile  = "1216*.ON";
+      // 27 Jan 04
+      //const char *onfile  = "12*.ON";
+      // 26 Jan 04
+      //const char *onfile  = "*.ON";
+      // 15 Feb 04
+      //const char *onfile  = "*.ON";
+
+
+     const char *mcfile  = "/data/MAGIC/mc_eth/magLQE_3/gh/0/0/G_M0_00_0_550*.root";
+      //const char *mcfile  = "/data/MAGIC/mc_eth/magLQE_4/gh/0/0/G_M0_00_0_550*.root";
+      //const char *mcfile  = "/data/MAGIC/mc_eth/magLQE_5/gh/0/0/G_M0_00_0_550*.root";
+      //-----------------------------------------------
+
+      // path for input for Mars
+      //TString inPath = "/.magic/magicserv01/scratch/";
+      //TString inPath = "/mnt/data17a/hbartko/";
+      //TString inPath = "~wittek/datacrab_feb04/";
+      //TString inPath = "~wittek/datacrab_26feb04/";
+     //TString inPath = "/.magic/magicserv01/scratch/David/CalibratedRuns/";
+     // 26 Jan 04, Hendrik
+     if (tag == "040126")
+       TString inPath = "/.magic/magicserv01/scratch/calibrated26/";
+
+     // 27 Jan 04, Hendrik
+     if (tag == "040127")
+        TString inPath = "/.magic/magicserv01/scratch/calibrated/";
+
+     // 27 Jan 04, David
+     //if (tag == "040127")
+     //TString inPath = "/mnt/magicserv01/scratch/David/CalibratedData/Crab/2004_01_27/";
+
+     // 15 Feb 04, David
+     if (tag == "040215")
+       TString inPath = "/mnt/magicserv01/scratch/David/CalibratedData/Crab/2004_02_15/";
+   
+
+      // path for output from Mars
+      //TString outPath = "~wittek/datacrab_feb04/";
+     //TString outPath = "~wittek/datacrab_01march04/";
+      TString outPath = "~wittek/datacrab_19mar04/";
+
+      //-----------------------------------------------
+
+      //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 GPad    = kFALSE;    // generate padding histograms?
+    Bool_t WPad    = kFALSE;   // write out padding histograms ?
+    Bool_t RPad    = kFALSE;   // read in padding histograms ?
+    Bool_t Wout    = kTRUE;   // 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  = 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, 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  = inPath;
+    fileON += onfile;
+    fileON += ".root";
+
+    TString fileOFF = inPath;
+    fileOFF += offfile;
+    fileOFF += ".root";
+
+    TString fileMC  = mcfile;
+    fileMC += mcfile;
+    fileMC += ".root";
+
+    gLog << "fileON, fileOFF, fileMC = " << fileON << ",  " 
+         << fileOFF << ",  " << fileMC   << 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(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
+    //if (typeInput == "ON")
+    //  TString file(onfile);
+    //else if (typeInput == "OFF")
+    //  TString file(offfile);
+    //else if (typeInput == "MC")
+    //  TString file(mcfile);
+
+    TString outNameImage = outPath;
+    outNameImage += tag;
+    outNameImage += "Hillas";
+    outNameImage += typeInput;
+    outNameImage += "1.root";
+    gLog << "padded data to be written onto : " << outNameImage << endl;
+
+    //--------------------------------------------------
+
+    //************************************************************
+    // generate histograms to be used in the padding
+    // 
+    // read ON, OFF and MC data files
+    // generate (or read in) the padding histograms for ON and OFF data
+    //                       and merge these histograms
+
+    MPad pad;
+    pad.SetName("MPad");
+    pad.SetDataType(typeInput);
+
+    // generate the padding histograms
+    if (GPad)
+    {
+      gLog << "=====================================================" << endl;
+      gLog << "Start generating the padding histograms" << endl;
+      //-----------------------------------------
+      // ON events
+
+      gLog << "-----------" << endl;
+      gLog << "ON events :" << endl;
+      gLog << "-----------" << endl;
+
+      MTaskList tliston;
+      MParList pliston;
+
+    MReadMarsFile  readON("Events", fileON);
+    readON.DisableAutoScheme();
+    //MCT1ReadPreProc readON(fileON);
+
+      //MFSelBasic selthetaon;
+      //selthetaon.SetCuts(-100.0, 29.5, 35.5);
+      //MContinue contthetaon(&selthetaon);
+
+      MBlindPixelCalc blindon;
+      blindon.SetUseBlindPixels();
+
+      MFSelBasic 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;
+
+    MReadMarsFile  readOFF("Events", fileOFF);
+    readOFF.DisableAutoScheme();
+    //      MCT1ReadPreProc readOFF(fileOFF);
+
+      MFSelBasic selthetaoff;
+      selthetaoff.SetCuts(-100.0, 29.5, 35.5);
+      MContinue contthetaoff(&selthetaoff);
+
+      MBlindPixelCalc blindoff;
+      blindoff.SetUseBlindPixels();
+
+      MFSelBasic 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();
+
+
+      //-----------------------------------------
+      // MC events
+
+      gLog << "------------" << endl;
+      gLog << "MC events :" << endl;
+      gLog << "------------" << endl;
+
+      MTaskList tlistmc;
+      MParList plistmc;
+
+    MReadMarsFile  readMC("Events", fileMC);
+    readMC.DisableAutoScheme();
+    //      MCT1ReadPreProc readMC(fileMC);
+
+      MFSelBasic selthetamc;
+      selthetamc.SetCuts(-100.0, 29.5, 35.5);
+      MContinue contthetamc(&selthetamc);
+
+      MBlindPixelCalc blindmc;
+      blindmc.SetUseBlindPixels();
+
+      MFSelBasic selbasicmc;
+      MContinue contbasicmc(&selbasicmc);
+
+      MHBlindPixels blindMC("BlindPixelsMC");
+      MFillH fillblindMC("BlindPixelsMC[MHBlindPixels]", "MBlindPixels");
+      fillblindMC.SetName("FillBlindMC");
+
+      MSigmabarCalc sigbarcalcmc;
+
+      MHSigmaTheta sigthMC("SigmaThetaMC");
+      MFillH fillsigthetaMC ("SigmaThetaMC[MHSigmaTheta]", "MMcEvt");
+      fillsigthetaMC.SetName("FillSigThetaMC");     
+
+      //*****************************
+      // entries in MParList
+    
+      plistmc.AddToList(&tlistmc);
+      InitBinnings(&plistmc);
+      plistmc.AddToList(&blindMC);
+      plistmc.AddToList(&sigthMC);
+
+
+      //*****************************
+      // entries in MTaskList
+    
+      tlistmc.AddToList(&readMC);
+      //tlistmc.AddToList(&contthetamc);
+
+      tlistmc.AddToList(&blindmc);
+
+      tlistmc.AddToList(&contbasicmc);
+      tlistmc.AddToList(&fillblindMC);
+      tlistmc.AddToList(&sigbarcalcmc);
+      tlistmc.AddToList(&fillsigthetaMC);
+
+      MProgressBar barmc;
+      MEvtLoop evtloopmc;
+      evtloopmc.SetParList(&plistmc);
+      evtloopmc.SetProgressBar(&barmc);
+
+      Int_t maxeventsmc = -1;
+      //Int_t maxeventsmc = 20000;
+      if ( !evtloopmc.Eventloop(maxeventsmc) )
+          return;
+
+      tlistmc.PrintStatistics(0, kTRUE);
+
+      blindMC.DrawClone();
+      sigthMC.DrawClone();
+
+      // save the histograms for the padding
+      TH2D *sigthmc     = sigthMC.GetSigmaTheta();
+      TH3D *sigpixthmc  = sigthMC.GetSigmaPixTheta();
+      TH3D *diffpixthmc = sigthMC.GetDiffPixTheta();
+
+      TH2D *blindidthmc = blindMC.GetBlindId();
+      TH2D *blindnthmc  = blindMC.GetBlindN();
+
+
+      //-----------------------------------------
+
+      gLog << "End of generating the padding histograms" << endl;
+      gLog << "=====================================================" << endl;
+
+      pad.MergeONOFFMC(sigthmc,      diffpixthmc,  sigpixthmc, 
+                       blindidthmc,  blindnthmc,
+                       sigthon,      diffpixthon,  sigpixthon, 
+                       blindidthon,  blindnthon,
+                       sigthoff,     diffpixthoff, sigpixthoff, 
+                       blindidthoff, blindnthoff);
+
+
+      if (WPad)
+      {
+        // write the padding histograms onto a file  ---------
+        pad.WritePaddingDist(outNameSigTh);     
+      }
+    }
+
+    // read the padding histograms ---------------------------
+    if (RPad)
+    {
+      pad.ReadPaddingDist(outNameSigTh);
+    }
+
+
+    //************************************************************
+
+  if (Wout)
+  {
+    gLog << "=====================================================" << endl;
+    gLog << "Start the padding" << endl;
+
+    //-----------------------------------------------------------
+    MTaskList tliston;
+    MParList pliston;
+
+    MObservatory observ;
+
+    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;
+
+    //MPedestalWorkaround waround;
+
+    // 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");
+
+    //if (typeInput ==  "ON")
+    //{
+    //   MCT1PointingCorrCalc pointcorr(sourceName, "MCT1PointingCorrCalc", 
+    //                                             "MCT1PointingCorrCalc");
+    //}
+    MSourcePosfromStarPos sourcefromstar;
+    if (typeInput == "ON")
+    {
+      sourcefromstar.SetSourceAndStarPosition(
+                               "Crab", 22,  0, 52, 5, 34, 32.0,
+      			   "Zeta-Tau", 21,  8, 33, 5, 37, 38.7);
+      sourcefromstar.AddStar("Tau114", 21, 56, 13, 5, 27, 38.1);
+      //sourcefromstar.AddFile("~wittek/datacrab_26feb04/positionsOn.4.txt",0);
+
+      if(inPath == "/.magic/magicserv01/scratch/calibrated/")
+      {
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/positions2stars.txt", 0);
+        //sourcefromstar.AddFile("~wittek/datacrab_26feb04/positionsNoStar.txt", 0);
+      }
+      else if(inPath == "/.magic/magicserv01/scratch/calibrated26/")
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/stars_2004_01_26", 0);
+
+      else if(inPath == "/mnt/magicserv01/scratch/David/CalibratedData/Crab/2004_02_15/")
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/positions040215.txt", 0);
+    }
+    else if (typeInput == "OFF")
+    {
+      if(inPath == "/.magic/magicserv01/scratch/calibrated/")
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/positionsOff.txt", 0);
+      else if(inPath == "/.magic/magicserv01/scratch/calibrated26/")
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/positions_2004_01_26", 0);
+      else if(inPath == "/mnt/magicserv01/scratch/David/CalibratedData/Crab/2004_02_15")
+        sourcefromstar.AddFile("~wittek/datacrab_26feb04/positions040215.txt", 0);
+    }
+
+
+    //MBlindPixelCalc blindbeforepad;
+    //blindbeforepad.SetUseBlindPixels();
+    //blindbeforepad.SetName("BlindBeforePadding");
+
+    //MBlindPixelCalc blind;
+    //blind.SetUseBlindPixels();
+    //blind.SetUseInterpolation();
+    //blind.SetName("BlindAfterPadding");
+
+    MSigmabarCalc sigbar;
+
+    //MBadPixelCalcRms blind;
+    MBlindPixelsCalc2 blind;
+    //blind.SetUseBlindPixels();
+    blind.SetUseInterpolation();
+    blind.SetCheckPedestalRms();
+    blind.SetName("BlindAfterPadding");
+
+    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(3.0, 2.5);
+    //clean.SetMethod(MImgCleanStd::kDemocratic);
+    clean.SetCleanRings(3); 
+
+
+    // 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(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("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);
+    pliston.AddToList(&observ);
+    InitBinnings(&pliston);
+
+    pliston.AddToList(&source);
+
+    //*****************************
+    // entries in MTaskList
+    
+    tliston.AddToList(&read);
+
+    //tliston.AddToList(&f1);
+    //tliston.AddToList(&f2);
+    tliston.AddToList(&apply);
+    //tliston.AddToList(&waround);
+    tliston.AddToList(&sourcefromstar);
+
+    //tliston.AddToList(&blindbeforepad);
+    //  tliston.AddToList(&pad); 
+    //  if (typeInput ==  "ON")
+    //  tliston.AddToList(&pointcorr);
+
+    tliston.AddToList(&sigbar);
+    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 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(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 << "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(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 << "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("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 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(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 << "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("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 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", "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
+    //
+    //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("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 ONOFFAnalysis : End of Job E_XX" << endl;
+    gLog << "=======================================================" << endl;
+ }
+  //---------------------------------------------------------------------
+
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONOFFCT1Analysis.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONOFFCT1Analysis.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/ONOFFCT1Analysis.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/Pedestals_Stability.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/Pedestals_Stability.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/Pedestals_Stability.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/RanForest.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/RanForest.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/RanForest.C	(revision 3781)
@@ -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", '=', kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    MFParticleId fhadrons("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-8-4/MagicSoft/Mars/macros/RanForest2.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/RanForest2.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/RanForest2.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/bootcampstandardanalysis.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/bootcampstandardanalysis.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/bootcampstandardanalysis.C	(revision 3781)
@@ -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): 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 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;
+
+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)
+                              )
+                              
+{
+
+  MRunIter pruns;
+  MRunIter cruns;
+  MRunIter druns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  MCalibrationCam::PulserColor_t color;
+
+  if (crun1 < 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("Could not find the correct colour: Type 'q' to exit, "
+                                  "green, blue, uv or ct1 to go on: ");
+          timer.TurnOff();
+          
+          if (input=="q\n")
+            return ;
+          
+          if (input=="green")
+            color = MCalibrationCam::kGREEN;
+          if (input=="blue")
+            color = MCalibrationCam::kBLUE;
+          if (input=="uv")
+            color = MCalibrationCam::kUV;
+          if (input=="ct1")
+            color = MCalibrationCam::kCT1;
+        }
+    }
+  
+  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);
+  if (usedisplay)
+    {
+      MStatusDisplay *display = new MStatusDisplay;
+      display->SetUpdateTime(3000);
+      display->Resize(850,700);
+      pedloop.SetDisplay(display);
+    }
+  pedloop.SetBadPixels(badcam);
+
+  if (!pedloop.Process())
+    return;
+
+  /****************************************/
+  /* SECOND LOOP: CALIBRATION COMPUTATION */
+  /****************************************/
+
+  //
+  // Now setup the new tasks for the calibration:
+  // ---------------------------------------------------
+  //
+  MCalibrationQECam qecam;
+  MJCalibration     calloop;
+  calloop.SetColor(color);
+  calloop.SetInput(&cruns);
+  //
+  // Use as signal extractor MExtractSignal:
+  //
+  calloop.SetExtractorLevel(1);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+  //
+  // The next two commands are for the display:
+  //
+  if (usedisplay)
+    {
+      calloop.SetDisplay(display);
+      calloop.SetDataCheck();
+    }
+  
+  //
+  // Apply rel. time calibration:
+  //
+  calloop.SetRelTimeCalibration();
+  //
+  // Use as arrival time extractor MArrivalTimeCalc2:
+  //
+  calloop.SetArrivalTimeLevel(2);
+  
+  //
+  // Do the event-loop:
+  //
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+  
+
+  /*************************************/
+  /* THIRD LOOP: PEDESTAL CALIBRATION  */
+  /*************************************/
+
+  //
+  // Create a empty Parameter List and an empty Task List
+  //
+  MParList  plist3;
+  MTaskList tlist3;
+  plist3.AddToList(&tlist3);
+  
+  //
+  // Now setup the tasks and tasklist to calculate the pedestal rms in number of photons
+  // -----------------------------------------------------------------------------------
+  //
+  
+  MCerPhotEvt    nphot;
+  MPedPhotCam    nphotrms;
+  
+  plist3.AddToList(&geomcam);
+
+  //
+  // 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);
+  
+  //tasks
+  MReadMarsFile read3("Events");
+  read3.DisableAutoScheme();
+  static_cast<MRead&>(read3).AddFiles(pruns);  
+
+  MExtractSignal   extsig;
+  MCalibrate       photcalc;
+  photcalc.SetCalibrationMode(MCalibrate::kFfactor);
+  //    MPedPhotCalc  photrmscalc;  //It doesn't exist yet
+  
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&extsig);
+  tlist3.AddToList(&photcalc);
+  //    tlist3.AddToList(&photrmscalc);
+  
+  //
+  // 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(&extsig);
+  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;
+}
+
+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-8-4/MagicSoft/Mars/macros/calibClasses.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibClasses.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibClasses.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/calibrate_data.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibrate_data.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibrate_data.C	(revision 3781)
@@ -0,0 +1,485 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 = "/mnt/Data/rootdata/CrabNebula/2004_01_27/";
+const TString defrout = "output_test.root";
+
+const Int_t defpedr [] = {12461};
+const Int_t defcalr [] = {12526,12527,12528,12529};
+const Int_t defdatar[] = {12517,12518};
+
+void calibrate_data(const TString inpath=defpath, 
+                    const Int_t psize=1, const Int_t pedruns[]=defpedr, 
+                    const Int_t csize=4, const Int_t calruns[]=defcalr, 
+                    const Int_t dsize=2, const Int_t dataruns[]=defdatar, 
+                    const TString resname=defrout)
+
+{
+
+  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);
+  }
+
+  MCalibrationCam::PulserColor_t color;
+
+  if (calruns[0] < 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("Could not find the correct colour: Type 'q' to exit, "
+                                  "green, blue, uv or ct1 to go on: ");
+          timer.TurnOff();
+          
+          if (input=="q\n")
+            return ;
+          
+          if (input=="green")
+            color = MCalibrationCam::kGREEN;
+          if (input=="blue")
+            color = MCalibrationCam::kBLUE;
+          if (input=="uv")
+            color = MCalibrationCam::kUV;
+          if (input=="ct1")
+            color = MCalibrationCam::kCT1;
+        }
+    }
+
+  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:
+  // ---------------------------------------------------
+  //
+  MCalibrationQECam qecam;
+  MJCalibration     calloop;
+  calloop.SetColor(color);
+  calloop.SetInput(&cruns);
+  //  calloop.SetFullDisplay();
+  //
+  // Use as signal extractor MExtractSignal2:
+  //
+  calloop.SetExtractorLevel(2);
+  //
+  // Set the corr. cams:
+  //
+  calloop.SetQECam(qecam);
+  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;
+  
+  MBadPixelsCam          &badbad  = calloop.GetBadPixels();
+  MCalibrationChargeCam  &calcam  = calloop.GetCalibrationCam();
+  MCalibrationRelTimeCam &timecam = calloop.GetRelTimeCam();
+
+  /************************************************************************/
+  /*                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);
+
+  MExtractSignal2     sigcalc;
+  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(&sigcalc);
+  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();
+      
+    }
+}
+
+
+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-8-4/MagicSoft/Mars/macros/calibration.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibration.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/calibration.C	(revision 3781)
@@ -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): 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. 
+// 
+/////////////////////////////////////////////////////////////////////////////
+const TString inpath = "/home/rootdata/BlindPixel/";
+const Int_t pedrun  = 20491;
+const Int_t calrun1 = 20494;
+const Int_t calrun2 = 20496;
+
+void calibration(const Int_t prun=pedrun, const Int_t crun1=calrun1, const Int_t crun2=calrun2)
+{
+  
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  MCalibrationCam::PulserColor_t color;
+
+  if (crun1 < 20000)
+    color = MCalibrationCam::kCT1;
+  else
+    color = FindColor((MDirIter*)&cruns);
+
+  if (color == MCalibrationCam::kNONE)
+    return;
+
+  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");
+
+  for (Int_t i=0;i<badcam.GetSize();i++)
+    if (badcam[i].IsBad())
+      cout << "Bad Pixel: " << i << endl;
+
+  MStatusDisplay *display = new MStatusDisplay;
+  display->SetUpdateTime(3000);
+  display->Resize(850,700);
+  
+  /************************************/
+  /* FIRST LOOP: PEDESTAL COMPUTATION */
+  /************************************/
+
+  MJPedestal pedloop;
+  pedloop.SetInput(&pruns);
+  pedloop.SetDisplay(display);
+  pedloop.SetBadPixels(badcam);
+
+  if (!pedloop.Process())
+    return;
+
+  //
+  // Now setup the tasks and for the calibration:
+  // ---------------------------------------------------
+  //
+  MJCalibration calloop;
+  calloop.SetColor(color);
+
+  //
+  // If you want only the most necessary plots, choose:
+  // calloop.SetDataCheck();
+  // 
+  // For everything, you ever dreamed of, choose:
+  // calloop.SetFullDisplay();
+
+  //
+  // If you want to calibrate the times as well, choose:
+  //
+  //  calloop.SetRelTimeCalibration();
+  calloop.SetInput(&cruns);
+  calloop.SetDisplay(display);
+  calloop.SetQECam(qecam);
+  calloop.SetBadPixels(pedloop.GetBadPixels());
+  if (!calloop.Process(pedloop.GetPedestalCam()))
+    return;
+  
+}
+
+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-8-4/MagicSoft/Mars/macros/collarea.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/collarea.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/collarea.C	(revision 3781)
@@ -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>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+void collarea(TString filename="camera.root", TString outname="")
+{
+    MStatusDisplay *d = new MStatusDisplay;
+    // redirect logging output to GUI, kFALSE to disable stream to stdout
+    d->SetLogStream(&gLog, kTRUE);
+
+    //
+    // 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);
+    MMcCollectionAreaCalc effi;
+
+    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();
+
+    //
+    // Now the histogram we wanted to get out of the data is
+    // filled and can be displayed
+    //
+    if ((d = magic.GetDisplay()))
+        d->AddTab("Collection Area");
+    else
+        new TCanvas("CollArea", "Result of the collection area calculation");
+
+    parlist.FindObject("MHMcCollectionArea")->DrawClone("nonew");
+
+
+    //
+    // 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("MHMcCollectionArea")->Write();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/comprob.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/comprob.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/comprob.C	(revision 3781)
@@ -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.
+ ! *
+ !
+ !   macro comprob.C
+ !
+ !   Author(s): Abelardo Moralejo
+ !   Author(s): Thomas Bretz, 2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+ !
+ !   Copyright: MAGIC Software Development, 2000-2002
+ !
+ !
+ \* ======================================================================== */
+
+// -------------------------------------------------------------------------
+//
+//  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-8-4/MagicSoft/Mars/macros/datatrigcheck.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/datatrigcheck.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/datatrigcheck.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/dohtml.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/dohtml.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/dohtml.C	(revision 3781)
@@ -0,0 +1,108 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 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 += "mgeom:";
+    sourcedir += "mgui:";
+    sourcedir += "mhbase:";
+    sourcedir += "mhist:";
+    sourcedir += "mhistmc:";
+    sourcedir += "mhvstime:";
+    sourcedir += "mimage:";
+    sourcedir += "mjobs:";
+    sourcedir += "mmain:";
+    sourcedir += "mmc:";
+    sourcedir += "mmontecarlo:";
+    sourcedir += "mpointing:";
+    sourcedir += "mranforest:";
+    sourcedir += "mraw:";
+    sourcedir += "mreflector:";
+    sourcedir += "mreport:";
+    sourcedir += "msignal:";
+    sourcedir += "msql:";
+    sourcedir += "mtools:";
+    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("pixvstime.C",     "MARS - Example how to plot a pixel value versus time");
+    html.Convert("sectorvstime.C",  "MARS - Example how to plot mean value of a camera sector versus time");
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estct1.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estct1.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estct1.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/estfit.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estfit.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estfit.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/estimate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estimate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/estimate.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/evtrate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/evtrate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/evtrate.C	(revision 3781)
@@ -0,0 +1,28 @@
+void evtrate()
+{
+    MParList plist;
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    read.AddFile("test-time.root");
+
+    MEventRateCalc calc;
+    calc.SetNumEvents(200);
+
+    MHVsTime rate("MEventRate.fRate");
+
+    MFillH fill(&rate, "MTime");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&calc);
+    tlist.AddToList(&fill);
+
+    MEvtLoop loop;
+    loop.SetParList(&plist);
+
+    loop.Eventloop();
+
+    rate.DrawClone();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/flux.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/flux.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/flux.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/fluxunfold.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/fluxunfold.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/fluxunfold.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/mccalibrate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/mccalibrate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/mccalibrate.C	(revision 3781)
@@ -0,0 +1,201 @@
+/* ======================================================================== *\
+   !
+   ! *
+   ! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+   ! * Software. It is distributed to you in the hope that it can be a useful
+   ! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+   ! * It is distributed WITHOUT ANY WARRANTY.
+   ! *
+   ! * Permission to use, copy, modify and distribute this software and its
+   ! * documentation for any purpose is hereby granted without fee,
+   ! * provided that the above copyright notice appear in all copies and
+   ! * that 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 is a version of the standard procedure to convert raw MC data 
+//  into calibrated data (photons per pixel) 
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MImgCleanStd.h"
+
+void mccalibrate()
+{
+  //
+  // 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 -----------------
+  TString* CalibrationFilename;
+  CalibrationFilename = new TString("../../gammas_nonoise/Gamma_zbin0_0*.root");
+  // File to be used for the calibration (must be a camera file without added noise)
+
+  Char_t* AnalysisFilename = "Gamma_zbin0*.root";  // File to be analyzed
+
+  Char_t* OutFilename      = "calibrated_data.root";       // Output file name
+
+
+  Int_t BinsHigh[2] = {5, 10}; // First and last FADC bin of the range to be integrated,
+  Int_t BinsLow[2]  = {5, 10}; // for high and low gain respectively.
+
+  // -------------------------------------------
+
+  //
+  // 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.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.
+
+  MExtractSignal    sigextract;
+  sigextract.SetSaturationLimit(240);
+
+  // Define ADC slices to be integrated in high and low gain:
+  sigextract.SetRange(BinsHigh[0], BinsHigh[1], BinsLow[0], BinsLow[1]);
+
+  MMcCalibrationUpdate  mccalibupdate;
+
+  MCalibrate calib; // Transforms signals from ADC counts into photons.
+  calib.SetCalibrationMode(MCalibrate::kFfactor);
+
+  //    MBlindPixelCalc   blind;
+  //    blind.SetUseInterpolation();
+
+  //
+  // 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).
+  //
+  MImgCleanStd      clean;
+
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+
+  MMcCalibrationCalc mccalibcalc;
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+
+  tlist.AddToList(&sigextract);
+  tlist.AddToList(&mccalibupdate);
+  tlist.AddToList(&calib);
+  tlist.AddToList(&clean);
+  //    tlist.AddToList(&blind);
+  tlist.AddToList(&hcalc);
+
+  tlist.AddToList(&mccalibcalc);
+
+  //
+  // Open output file:
+  //
+  MWriteRootFile write(OutFilename); // Writes output
+  write.AddContainer("MGeomCam",            "RunHeaders");
+  write.AddContainer("MMcConfigRunHeader",  "RunHeaders");
+  write.AddContainer("MMcCorsikaRunHeader", "RunHeaders");
+  write.AddContainer("MMcFadcHeader",       "RunHeaders");
+  write.AddContainer("MMcRunHeader",        "RunHeaders");
+  write.AddContainer("MMcTrigHeader",       "RunHeaders");
+  write.AddContainer("MRawRunHeader",       "RunHeaders");
+  write.AddContainer("MSrcPosCam",          "RunHeaders");
+
+
+  write.AddContainer("MMcEvt",        "Events");
+  write.AddContainer("MMcTrig",       "Events");
+  write.AddContainer("MRawEvtHeader", "Events");
+  write.AddContainer("MCerPhotEvt",   "Events");
+  write.AddContainer("MPedPhotCam",   "Events");
+
+  //
+  // First loop: Calibration loop
+  //
+
+  MProgressBar bar;
+  bar.SetWindowName("Calibrating...");
+
+  MEvtLoop evtloop;
+  evtloop.SetProgressBar(&bar);
+  evtloop.SetParList(&plist);
+
+  if (CalibrationFilename)
+    {
+      if (!evtloop.Eventloop())
+	return;
+      mccalibcalc->GetHist()->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, "All");
+  tlist.RemoveFromList(&read);
+
+  bar.SetWindowName("Writing...");
+
+  tlist.RemoveFromList(&clean);
+  tlist.RemoveFromList(&hcalc);
+  tlist.RemoveFromList(&mccalibcalc);
+
+  tlist.AddToList(&write);            // Add task to write output.
+
+  if (!evtloop.Eventloop())
+    return;
+
+
+  tlist.PrintStatistics();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/mergecamera.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/mergecamera.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/mergecamera.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/merpp.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/merpp.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/merpp.C	(revision 3781)
@@ -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): Thomas Bretz  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// This is an easy implementation of the Merging process (as root Macro)
+//
+// 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")
+//
+/////////////////////////////////////////////////////////////////////////////
+
+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-8-4/MagicSoft/Mars/macros/multidimdist.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/multidimdist.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/multidimdist.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/multidimdist2.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/multidimdist2.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/multidimdist2.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/optPad.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/optPad.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/optPad.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/pedestalstudies.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedestalstudies.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedestalstudies.C	(revision 3781)
@@ -0,0 +1,505 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+//////////////////////////////////////////////////////////////////////////////
+//
+// pedestalstudies.C
+//
+// macro to observe the pedestals and pedestalRMS with the number of FADC 
+// slices summed up. 
+//
+// In order to use this macro, you have to uncomment the following 
+// line in MPedCalcPedRun (line 214):
+//
+// fNumHiGainSamples = runheader->GetNumSamplesHiGain() & ~1;
+//
+//
+/////////////////////////////////////////////////////////////////////////////////
+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:
+      //		
+      //sigcalc.SetRange(1,14,1,14);
+      MPedCalcPedRun pedcalc;
+      pedcalc.SetNumHiGainSamples((Byte_t)samples);
+      
+      MExtractSignal  sigcalc;
+      sigcalc.SetRange(0,samples-1,0,samples-1);
+  
+      //
+      // 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);
+
+
+  TCanvas *canvas2 = new TCanvas("PedstudOut","Pedestal Studies Outer Pixels",600,900);
+  canvas2->Divide(2,3);
+  canvas2->cd(1);
+
+
+  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");
+  //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);
+
+
+}
+
+
+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-8-4/MagicSoft/Mars/macros/pedestalvstime.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedestalvstime.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedestalvstime.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/pedphotcalc.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedphotcalc.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedphotcalc.C	(revision 3781)
@@ -0,0 +1,643 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 "MExtractSignal.h" 
+#include "MCerPhotEvt.h"
+#include "MCalibrate.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;
+
+static 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;      
+}
+
+
+
+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)
+                 )
+{
+  
+  MRunIter pruns;
+  MRunIter cruns;
+
+  pruns.AddRun(prun,inpath);
+
+  if (crun2==0)
+    cruns.AddRun(crun1,inpath);
+  else
+    cruns.AddRuns(crun1,crun2,inpath);
+
+  MCalibrationCam::PulserColor_t color;
+
+  if (crun1 < 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("Could not find the correct colour: Type 'q' to exit, "
+                                  "green, blue, uv or ct1 to go on: ");
+          timer.TurnOff();
+          
+          if (input=="q\n")
+            return ;
+          
+          if (input=="green")
+            color = MCalibrationCam::kGREEN;
+          if (input=="blue")
+            color = MCalibrationCam::kBLUE;
+          if (input=="uv")
+            color = MCalibrationCam::kUV;
+          if (input=="ct1")
+            color = MCalibrationCam::kCT1;
+        }
+    }
+
+  //
+  // 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.SetColor(color);
+  calloop.SetInput(&cruns);
+  //
+  // Use as signal extractor MExtractSignal:
+  //
+  calloop.SetExtractorLevel(1);
+  //
+  // 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);  
+
+  MExtractSignal  sigcalc;
+  MCalibrate      photcalc;
+  photcalc.SetCalibrationMode(MCalibrate::kFfactor);
+  MPedPhotCalc    pedphotcalc;  
+
+  tlist3.AddToList(&read3);
+  tlist3.AddToList(&geomapl);
+  tlist3.AddToList(&sigcalc);
+  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-8-4/MagicSoft/Mars/macros/pedvsevent.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedvsevent.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pedvsevent.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/pixfirerate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pixfirerate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pixfirerate.C	(revision 3781)
@@ -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): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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);
+
+    Double_t threshold[] = { 10, 20, 100, 200, -1 };
+
+    Int_t cnt = 0;
+    while (threshold[cnt]>0) cnt++;
+
+    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);
+    }
+
+    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-8-4/MagicSoft/Mars/macros/pixsatrate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pixsatrate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pixsatrate.C	(revision 3781)
@@ -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): Abelardo Moralejo <mailto:moralejo@pd.infn.it>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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);
+
+    MHTriggerLvl0 trighi(254, "SaturationHi", "Saturation Rate of Hi Gains");
+    MHTriggerLvl0 triglo(254, "SaturationLo", "Saturation Rate of Lo Gains");
+    trighi.SetType(1);
+    triglo.SetType(2);
+
+    MFillH fillhi(&trighi, "MRawEvtData");
+    MFillH filllo(&triglo, "MRawEvtData");
+    tlist.AddToList(&fillhi);
+    tlist.AddToList(&filllo);
+
+    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-8-4/MagicSoft/Mars/macros/plot.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/plot.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/plot.C	(revision 3781)
@@ -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): 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
+!
+!
+\* ======================================================================== */
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+void plot()
+{
+    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", '=', kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for Non-Gammas
+    MFParticleId fhadrons("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-8-4/MagicSoft/Mars/macros/plot2.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/plot2.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/plot2.C	(revision 3781)
@@ -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, 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
+!
+!
+\* ======================================================================== */
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a 2D histogram using Mars
+//
+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", '=', kGAMMA);
+    tlist.AddToList(&fgamma);
+
+    // Create a filter for the non-gamma events
+    MFParticleId fhadrons("MMcEvt", '!', kGAMMA);
+    tlist.AddToList(&fhadrons);
+
+    // -------------------------------------------------------
+    //
+    // set the name of the variable to plot and the binning
+    //
+    MGeomCamMagic cam;
+    plist.AddToList(&cam);
+
+    TString vary("MHillas.fWidth*MGeomCam.fConvMm2Deg");
+    TString varx("MHillas.fLength*MGeomCam.fConvMm2Deg");
+
+    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-8-4/MagicSoft/Mars/macros/pointing.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pointing.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pointing.C	(revision 3781)
@@ -0,0 +1,347 @@
+/*
+ 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("ccdata.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");
+    h0.SetName("Mjd");
+    h1.SetName("Zd");
+    h2.SetName("Az");
+    h3.SetName("State");
+
+    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 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);
+
+    // -----------------------------------------------
+
+    //
+    // 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);
+
+    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();
+
+    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;
+    }
+
+    //TGraph gr;
+
+    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();
+/*
+    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();
+*/
+    p = new TPad("", "", 0.6, 0, 1, 0.29);
+    p->Draw();
+    p->cd();
+
+    gStyle->SetOptStat(1110);
+    gStyle->SetStatFormat(".2g");
+
+    MH3 *mh3 = (MH3*)h4.DrawClone("nonew");
+
+    mh3->GetHist()->SetXTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetYTitle("");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+
+    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();
+
+    p = new TPad("", "", 0.6, 0.29, 1, 0.42);
+    p->Draw();
+    p->cd();
+
+    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();
+
+    p = new TPad("", "", 0.6, 0.71, 1, 1);
+    p->Draw();
+    p->cd();
+
+    gStyle->SetOptStat(1110);
+    gStyle->SetStatFormat(".2g");
+
+    mh3 = (MH3*)h5.DrawClone("nonew");
+
+    mh3->GetHist()->SetXTitle("Zd [\\circ]");
+    mh3->GetHist()->SetYTitle("\\Delta [arcmin]");
+    mh3->GetHist()->SetTitle("Control deviation of the motors");
+    mh3->GetHist()->SetStats(1);
+    mh3->GetHist()->Draw("box");
+
+    c.cd();
+
+    p = new TPad("", "", 0.6, 0.42, 1, 0.71);
+    p->Draw();
+    p->cd();
+
+    gPad->SetBorderMode(0);
+
+    hvt = (MHVsTime*)h1.DrawClone("nonew");
+
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+    if (hvt->GetGraph()->GetN())
+    {
+        hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+        hvt->GetGraph()->GetHistogram()->SetYTitle("Zd [\\circ]");
+        hvt->GetGraph()->GetHistogram()->SetTitle("Zd vs. Time");
+        hvt->GetGraph()->GetHistogram()->SetStats(0);
+    }
+
+    /*
+    TCanvas &c = d->AddTab("Sky3");
+
+    c.cd();
+
+    p = new TPad("", "", 0, 0, 1, 1);
+    p->Draw();
+    p->cd();
+
+    hvt = (MHVsTime*)h1.DrawClone("nonew");
+    hvt->GetGraph()->SetMarkerStyle(kFullDotSmall);
+    hvt->GetGraph()->GetHistogram()->SetXTitle("Time");
+    hvt->GetGraph()->GetHistogram()->SetYTitle("Zd [\\circ]");
+    hvt->GetGraph()->GetHistogram()->SetTitle("Zd vs. Time");
+    hvt->GetGraph()->GetHistogram()->SetStats(0);
+
+    */
+
+    //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-8-4/MagicSoft/Mars/macros/pointspreadfunction.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pointspreadfunction.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/pointspreadfunction.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readCT1.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readCT1.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readCT1.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readMagic.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readMagic.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readMagic.C	(revision 3781)
@@ -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  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;
+}
+
+MHCamera display[4];
+
+TCanvas   *c;
+MParList  *fParList;
+MTaskList *fTaskList;
+
+Int_t PreProcess(MParList *plist)
+{
+    fParList = plist;
+    fTaskList = (MTaskList*)plist->FindObject("MTaskList");
+
+    MGeomCam *geomcam = (MGeomCam*)plist->FindObject("MGeomCam");
+
+    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;
+}
+
+Int_t Process()
+{
+    MReadMarsFile *read = (MReadMarsFile*)fTaskList->FindObject("MRead");
+    MClone *clone = (MClone*)fTaskList->FindObject("MClone");
+    MImgCleanStd *clean = (MImgCleanStd*)fTaskList->FindObject("MImgCleanStd");
+    MGeomCam *geom = (MGeomCam*)fParList->FindObject("MGeomCam");
+
+    cout << "Event #" << read->GetNumEntry() << ":" << endl;
+
+    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"));
+
+    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();
+    }
+
+    ((MHillas*)fParList->FindObject("MHillas"))->Print(*geom);
+    ((MHillasExt*)fParList->FindObject("MHillasExt"))->Print(*geom);
+    ((MNewImagePar*)fParList->FindObject("MNewImagePar"))->Print(*geom);
+
+    return HandleInput();
+}
+
+Int_t PostProcess()
+{
+    delete c;
+}
+
+void readMagic(const char *fname="../Proton*.root")
+{               
+    MParList  plist;
+    MTaskList tlist;
+
+    plist.AddToList(&tlist);
+
+    MReadMarsFile read("Events", fname);
+    read.DisableAutoScheme();
+
+    MGeomApply geomapl;
+    MPrint print1("MMcEvt");
+    MPrint print2("MRawEvtHeader");
+    print1.EnableSkip();
+    print2.EnableSkip();
+
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+    MCerPhotAnal2     ncalc;
+    MBlindPixelCalc   blind;
+    blind.SetUseInterpolation();
+    MClone            clone("MCerPhotEvt");
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MTaskInteractive  mytask;
+
+    mytask.SetPreProcess(PreProcess);
+    mytask.SetProcess(Process);
+
+    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);
+
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    if (!evtloop.Eventloop())
+        return;
+
+    tlist.PrintStatistics();
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readcurrents.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readcurrents.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readcurrents.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readin.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readin.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readin.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readpix.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readpix.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readpix.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readraw.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readraw.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readraw.C	(revision 3781)
@@ -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 readraw()
+{
+    //
+    // 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-8-4/MagicSoft/Mars/macros/readrep.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readrep.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readrep.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/readrfl.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readrfl.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/readrfl.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/rootlogon.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/rootlogon.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/rootlogon.C	(revision 3781)
@@ -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  12/2000 (tbretz@uni-sw.gwdg.de)
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+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;
+
+    TString dir = 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+"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+"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+"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+"mtools");
+
+    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-8-4/MagicSoft/Mars/macros/runbook.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/runbook.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/runbook.C	(revision 3781)
@@ -0,0 +1,99 @@
+void Wrap(TString &str)
+{
+    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)
+{
+    cout << fname << endl;
+
+    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())
+    {
+        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;
+        }
+
+        if (!line(r0).IsNull())
+            print = !line(r1).IsNull();
+
+        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]")
+{
+    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;
+        }
+    }
+
+    MDirIter Next;
+    Next.AddDirectory("/home/MAGIC/online_data/runbook", "CC_*.rbk");
+
+    TString name;
+    while (1)
+    {
+        name=Next();
+        if (name.IsNull())
+            break;
+
+        ProcessFile(name, d);
+    }
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sectorvstime.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sectorvstime.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sectorvstime.C	(revision 3781)
@@ -0,0 +1,94 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  This macro is an example of how to plot the value of a part of the
+// camera or the whole camera.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+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-8-4/MagicSoft/Mars/macros/spline.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/spline.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/spline.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/star.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/star.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/star.C	(revision 3781)
@@ -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, 5/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  STAR - STandard Analysis and Reconstruction
+//
+//  This macro is the standard converter to convert raw data into image
+//  parameters
+//
+/////////////////////////////////////////////////////////////////////////////
+
+void star()
+{
+    //
+    // This is a demonstration program which calculates the image 
+    // parameters from a Magic raw data 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);
+
+    //
+    // 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-8-4/MagicSoft/Mars/macros/starfield.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starfield.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starfield.C	(revision 3781)
@@ -0,0 +1,55 @@
+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 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);
+    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-8-4/MagicSoft/Mars/macros/starmc.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmc.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmc.C	(revision 3781)
@@ -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): 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("../../gammas_nonoise/Gamma_zbin0_90_*.root");
+  // File to be used in the calibration (must be a camera file without added noise)
+
+  Char_t* AnalysisFilename = "Gamma_zbin*.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] = {4., 3.}; // Tail cuts for image analysis
+
+  Int_t BinsHigh[2] = {5, 10}; // First and last FADC bin of the range to be integrated,
+  Int_t BinsLow[2]  = {5, 10}; // for high and low gain respectively.
+
+  // -------------------------------------------
+
+  //
+  // 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.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.
+
+  MExtractSignal    sigextract;
+  sigextract.SetSaturationLimit(240);
+  // Define ADC slices to be integrated in high and low gain:
+  sigextract.SetRange(BinsHigh[0], BinsHigh[1], BinsLow[0], BinsLow[1]);
+
+  MMcCalibrationUpdate  mccalibupdate;
+
+  MCalibrate calib; // Transforms signals from ADC counts into photons.
+  calib.SetCalibrationMode(MCalibrate::kFfactor);
+
+  //    MBlindPixelCalc   blind;
+  //    blind.SetUseInterpolation();
+
+  MImgCleanStd      clean(CleanLev[0], CleanLev[1]); // Applies tail cuts to image.
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  MHillasSrcCalc    scalc; // Calculates source-dependent Hillas parameters 
+
+  MMcCalibrationCalc mccalibcalc;
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&geom);
+  tlist.AddToList(&pcopy);
+
+  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("MMcEvt",        "Events");
+  write1.AddContainer("MHillas",       "Events");
+  write1.AddContainer("MHillasExt",    "Events");
+  write1.AddContainer("MHillasSrc",    "Events");
+  write1.AddContainer("MNewImagePar",  "Events");
+
+  if (OutFilename2)
+    {
+      MWriteRootFile write2(OutFilename2.Data()); // Writes output2
+      write2.AddContainer("MRawRunHeader", "RunHeaders");
+      write2.AddContainer("MMcRunHeader",  "RunHeaders");
+      write2.AddContainer("MSrcPosCam",    "RunHeaders");
+      write2.AddContainer("MMcEvt",        "Events");
+      write2.AddContainer("MHillas",       "Events");
+      write2.AddContainer("MHillasExt",    "Events");
+      write2.AddContainer("MHillasSrc",    "Events");
+      write2.AddContainer("MNewImagePar",  "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->GetHist()->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.
+
+  tlist.AddToList(&scalc);            // Calculates Source-dependent Hillas parameters
+
+
+  // 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-8-4/MagicSoft/Mars/macros/starmc2.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmc2.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmc2.C	(revision 3781)
@@ -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): 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_run.root"; // File to be analyzed
+  Char_t* OutFilename      = "star.root";        // Output file name
+
+  Float_t CleanLev[2] = {4., 3.}; // Tail cuts for image analysis
+
+  // ------------------------------------------------------------------
+
+  //
+  // 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.SetReadyToSave();
+
+  plist.AddToList(&src);
+
+  //
+  // Now setup the tasks and tasklist:
+  // ---------------------------------
+  //
+  MReadMarsFile read("Events");
+
+  read.AddFile(AnalysisFilename);
+
+  read.DisableAutoScheme();
+
+  MImgCleanStd      clean(CleanLev[0], CleanLev[1]); // Applies tail cuts to image.
+
+  MHillasCalc       hcalc; // Calculates Hillas parameters not dependent on source position.
+  MHillasSrcCalc    scalc; // Calculates source-dependent Hillas parameters 
+
+  tlist.AddToList(&read);
+  tlist.AddToList(&clean);
+  //    tlist.AddToList(&blind);
+  tlist.AddToList(&hcalc);
+  tlist.AddToList(&scalc); // Calculates Source-dependent Hillas parameters
+
+  //
+  // Open output file:
+  //
+  MWriteRootFile write(OutFilename); // Writes output
+  write.AddContainer("MRawRunHeader", "RunHeaders");
+  write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+  write.AddContainer("MSrcPosCam",    "RunHeaders");
+  write.AddContainer("MMcEvt",        "Events", kFALSE);
+  write.AddContainer("MHillas",       "Events");
+  write.AddContainer("MHillasExt",    "Events");
+  write.AddContainer("MHillasSrc",    "Events");
+  write.AddContainer("MNewImagePar",  "Events");
+
+  tlist.AddToList(&write);            // Add task to write output.
+
+  //
+  // 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-8-4/MagicSoft/Mars/macros/starmcstereo.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmcstereo.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starmcstereo.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/starplot.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starplot.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/starplot.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/status.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/status.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/status.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/sumcurrents.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumcurrents.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumcurrents.C	(revision 3781)
@@ -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, 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:
+    // ---------------------------------
+    //
+
+    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);
+
+    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();
+
+    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} [nA]");
+    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");
+}
+
+// -------------------------------------------------------------------------
+//
+//  plot.C
+//
+//  This macro shows how to fill and display a histogram using Mars
+//
+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-8-4/MagicSoft/Mars/macros/sumevents.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumevents.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumevents.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/sumeventserr.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumeventserr.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumeventserr.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/sumeventsrms.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumeventsrms.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumeventsrms.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/sumpedestalrms.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumpedestalrms.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumpedestalrms.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/sumpedestals.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumpedestals.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/sumpedestals.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/tar.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/tar.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/tar.C	(revision 3781)
@@ -0,0 +1,31 @@
+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 "+name+"/.rootrc "+name+"/*";
+
+    cout << "Executing: " << cmd << endl;
+
+    gSystem->Exec(cmd);
+    gSystem->Exec("gzip -9 "+name+".tar");
+
+    gSystem->cd(name);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/macros/testenv.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/testenv.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/testenv.C	(revision 3781)
@@ -0,0 +1,79 @@
+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-8-4/MagicSoft/Mars/macros/threshold.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/threshold.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/threshold.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/triglvl2.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/triglvl2.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/triglvl2.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/trigrate.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/trigrate.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/trigrate.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/unfold.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/unfold.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/unfold.C	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/macros/weights.C
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/macros/weights.C	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/macros/weights.C	(revision 3781)
@@ -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): Marcos Lopez, 10/2003 <mailto:marcos@gae.ucm.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// 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-8-4/MagicSoft/Mars/magic_t.xpm
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/magic_t.xpm	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/magic_t.xpm	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/magiclogo.xpm
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/magiclogo.xpm	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/magiclogo.xpm	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/AnalysisIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/AnalysisIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/AnalysisIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/AnalysisLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/AnalysisLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/AnalysisLinkDef.h	(revision 3781)
@@ -0,0 +1,81 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCerPhotPix+;
+#pragma link C++ class MCerPhotEvt+;
+#pragma link C++ class MCerPhotEvtIter+;
+#pragma link C++ class MCerPhotAnal+;
+#pragma link C++ class MCerPhotAnal2+;
+#pragma link C++ class MCerPhotCalc+;
+
+#pragma link C++ class MCameraData+;
+
+#pragma link C++ class MBlindPixels+;
+#pragma link C++ class MBlindPixelCalc+;
+#pragma link C++ class MBlindPixelsCalc2+;
+
+#pragma link C++ class MPedestalPix+;
+#pragma link C++ class MHPedestalPix+;
+#pragma link C++ class MPedestalCam+;
+#pragma link C++ class MHPedestalCam+;
+#pragma link C++ class MPedCalcPedRun+;
+#pragma link C++ class MPedPhotCalc+;
+#pragma link C++ class MMcPedestalCopy+;
+#pragma link C++ class MMcPedestalNSBAdd+;
+#pragma link C++ class MGeomApply+;
+
+#pragma link C++ class MHadronness+;
+
+#pragma link C++ class MCompProbCalc+;
+#pragma link C++ class MMultiDimDistCalc+;
+
+#pragma link C++ class MEnergyEst+;
+#pragma link C++ class MEnergyEstimate+;
+#pragma link C++ class MEnergyEstParam+;
+#pragma link C++ class MEnergyEstParamDanielMkn421+;
+
+#pragma link C++ class MMatrixLoop+;
+
+#pragma link C++ class MSigmabar+;
+#pragma link C++ class MSigmabarCalc+;
+#pragma link C++ class MSigmabarParam+;
+
+#pragma link C++ class MEventRate+;
+#pragma link C++ class MEventRateCalc+;
+
+#pragma link C++ class MCT1PadSchweizer+;
+#pragma link C++ class MCT1PadONOFF+;
+#pragma link C++ class MPad+;
+
+#pragma link C++ class MCT1PointingCorrCalc+;
+
+#pragma link C++ class MParameterI+;
+#pragma link C++ class MParameterD+;
+//#pragma link C++ class MParameters+;
+
+#pragma link C++ class MMcTriggerLvl2+;
+#pragma link C++ class MMcTriggerLvl2Calc+;
+
+#pragma link C++ class MCT1Supercuts+;
+#pragma link C++ class MCT1SupercutsCalc+;
+#pragma link C++ class MCT1FindSupercuts+;
+#pragma link C++ class MSupercuts+;
+#pragma link C++ class MSupercutsCalc+;
+#pragma link C++ class MFindSupercuts+;
+#pragma link C++ class MMinuitInterface+;
+#pragma link C++ class MFiltercutsCalc+;
+
+#pragma link C++ class MPedestalWorkaround+;
+
+#pragma link C++ class MSourcePosfromStarPos+;
+#pragma link C++ class MMcCalibrationUpdate+;
+
+#pragma link C++ class MPedPhotCam+;
+#pragma link C++ class MPedPhotPix+;
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.cc	(revision 3781)
@@ -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): 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBlindPixelCalc
+//
+//  This is the specific image cleaning for a list of pixels. This task
+//  sets the pixels listed in fPixelsIdx to unused so they should not be
+//  used for analysis (eg calculation of hillas parameters).
+//
+//  You can use MBlindPixelCalc::SetUseInterpolation to replaced the
+//  blind pixels by the average of its neighbors instead of unmapping
+//  them. If you want to include the central pixel use
+//  MBlindPixelCalc::SetUseCentralPixel.
+//
+//  You have three options:
+//   1) Call SetUseBlindPixels():
+//      This will take an existing MBlindPixels container filled from
+//      elsewhere (eg. MCT1ReadPreProc) and use this pixels as blind
+//      pixels.
+//   2) Call SetPixels():
+//      This will setup an array with pixel numbers. These pixels are used
+//      as blind pixels.
+//   3) Neither 1) nor 2)
+//      This options 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.
+//
+//  If neither an array of pixels is given (or its size is 0) and
+//  MMcRunHeader couldn't be found the task removes itself from the
+//  tasklist.
+//
+//  Implemented star fields:
+//   - Crab: 400, 401, 402, 437, 438, 439
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   [MBlindPixels]
+//
+//  Output Containers:
+//   MCerPhotEvt
+//   MBlindPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBlindPixelCalc.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MBlindPixels.h"
+
+#include "MMcRunHeader.hxx"
+
+ClassImp(MBlindPixelCalc);
+
+using namespace std;
+
+static const TString gsDefName  = "MBlindPixelCalc";
+static const TString gsDefTitle = "Find hot spots (star, broken pixels, etc)";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBlindPixelCalc::MBlindPixelCalc(const char *name, const char *title)
+    : fFlags(0)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Try to find or create MBlindPixels in parameter list.
+//  - get the MCerPhotEvt 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 MBlindPixelCalc::PreProcess (MParList *pList)
+{
+    if (TESTBIT(fFlags, kUseBlindPixels))
+        fPixels = (MBlindPixels*)pList->FindObject(AddSerialNumber("MBlindPixels"));
+    else
+        fPixels = (MBlindPixels*)pList->FindCreateObj(AddSerialNumber("MBlindPixels"));
+    if (!fPixels)
+	return kFALSE; 
+    
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPed = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+        *fLog << warn << dbginf << "No camera geometry available... can't use interpolation." << endl;
+
+    if (TESTBIT(fFlags, kUseBlindPixels))
+        return kTRUE;
+
+    const UShort_t size = fPixelsIdx.GetSize();
+
+    if (size == 0)
+    {
+        if (!pList->FindObject("MMcRunHeader"))
+        {
+            *fLog << warn << "Warning - Neither blind pixels are given nor a MMcRunHeader was found... removing MBlindPixelCalc from list." << endl;
+            return kSKIP;
+        }
+        return kTRUE;
+    }
+
+    // Set as blind pixels the global blind pixels, which are given
+    // through the macros
+
+    UShort_t numids = fPixelsIdx.GetSize();
+
+    for(Int_t i = 0; i<numids; i++)
+	fPixels->SetPixelBlind(fPixelsIdx[i]);
+
+    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.
+//
+//  NT: Informations about the interpolated pedestals are added. 
+//      When the option Interpolated is called, the blind pixel with the new
+//      values of signal and fluttuation is included in the calculation of
+//      the Image Parameters.
+//
+void MBlindPixelCalc::Interpolate() const
+{
+    const UShort_t entries = fGeomCam->GetNumPixels();
+
+    //
+    // Create arrays
+    //
+    Double_t *nphot  = new Double_t[entries];
+    Double_t *perr   = new Double_t[entries];
+    Double_t *ped    = new Double_t[entries];
+    Double_t *pedrms = new Double_t[entries];
+ 
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!fPixels->IsBlind(i))
+            continue;
+
+        //
+        // Get a pointer to this pixel. If it is not yet existing
+        // create a new entry for this pixel in MCerPhotEvt
+        //
+        const MCerPhotPix *pix = fEvt->GetPixById(i);
+        if (!pix)
+            pix = fEvt->AddPixel(i, 0, 0);
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix &gpix = (*fGeomCam)[i];
+        const MPedestalPix &ppix = (*fPed)[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();
+        ped[i]    = nucp ? 0 : ppix.GetPedestal();
+        perr[i]   = nucp ? 0 : Sqr(pix->GetErrorPhot());
+        pedrms[i] = nucp ? 0 : Sqr(ppix.GetPedestalRms());
+
+        //
+	// The values are rescaled to the small pixels area for the right comparison
+        //
+        const Double_t ratio = fGeomCam->GetPixRatio(i);
+
+        nphot[i]  *= ratio;
+	ped[i]    *= ratio;
+        perr[i]   *= Sqr(ratio);
+	pedrms[i] *= Sqr(pedrms[i]);
+
+        //
+        // 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 (fPixels->IsBlind(nidx))
+                continue;
+
+            //
+            // Check whether the neighbor has a signal stored
+            //
+            const MCerPhotPix *evtpix = fEvt->GetPixById(nidx);
+            if (!evtpix)
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t nratio = fGeomCam->GetPixRatio(nidx);
+            MPedestalPix &nppix = (*fPed)[nidx];
+
+            //
+	    //The error is calculated as the quadratic sum of the errors
+	    //
+            ped[i]    += nratio*nppix.GetPedestal();
+            nphot[i]  += nratio*evtpix->GetNumPhotons();
+            perr[i]   += Sqr(nratio*evtpix->GetErrorPhot());
+	    pedrms[i] += Sqr(nratio*nppix.GetPedestalRms());
+
+            num++;
+        }
+
+        //
+	// Now the mean is calculated and the values rescaled back to the pixel area
+        //
+	nphot[i] /= num*ratio;
+        ped[i]   /= num*ratio;
+        perr[i]   = TMath::Sqrt(perr[i]/num)*ratio;
+        pedrms[i] = TMath::Sqrt(pedrms[i]/num)*ratio;
+
+    }
+
+    //
+    // Now the new pixel values are calculated and can be replaced in
+    // the corresponding containers
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Do not use blind neighbors
+        //
+        if (!fPixels->IsBlind(i))
+            continue;
+
+        //
+        // It must exist, we have created it in the loop before.
+        //
+        fEvt->GetPixById(i)->Set(nphot[i], perr[i]);
+        (*fPed)[i].Set(ped[i], pedrms[i]);
+    }
+
+    //
+    // Delete the intermediat arrays
+    //
+    delete nphot;
+    delete perr;
+    delete ped;
+    delete pedrms;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Removes all blind pixels from the analysis by setting their state
+//  to unused.
+//
+void MBlindPixelCalc::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++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        if (fPixels->IsBlind(pix.GetPixId()))
+            pix.SetPixelUnused();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Treat the blind pixels
+//
+Int_t MBlindPixelCalc::Process()
+{
+    if (TESTBIT(fFlags, kUseInterpolation) && fGeomCam)
+        Interpolate();
+    else
+        Unmap();
+
+    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 MBlindPixelCalc::ReInit(MParList *pList)
+{
+    if (TESTBIT(fFlags, kUseBlindPixels))
+        return kTRUE;
+
+    //
+    // If pixels are given by the user, we are already done
+    //
+    if (fPixelsIdx.GetSize() > 0)
+        return kTRUE;
+
+    //
+    // Delete the old array holding the blind pixels for the last file
+    //
+    fPixels->Clear();
+
+    if (!fGeomCam->InheritsFrom("MGeomCamMagic"))
+    {
+        *fLog << warn << "MBlindPixelCalc::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 << "MBlindPixelCalc::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
+    //
+    fPixels->SetPixelBlind(400);
+    fPixels->SetPixelBlind(401);
+    fPixels->SetPixelBlind(402);
+    fPixels->SetPixelBlind(437);
+    fPixels->SetPixelBlind(438);
+    fPixels->SetPixelBlind(439);
+
+    *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;
+}
+
+void MBlindPixelCalc::StreamPrimitive(ofstream &out) const
+{
+    out << "   MBlindPixelCalc " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (TESTBIT(fFlags, kUseInterpolation))
+        out << "   " << GetUniqueName() << ".SetUseInterpolation();" << endl;
+    if (TESTBIT(fFlags, kUseCentralPixel))
+        out << "   " << GetUniqueName() << ".SetUseCentralPixel();" << endl;
+
+    if (fPixelsIdx.GetSize()==0)
+        return;
+
+    out << "   {" << endl;
+    out << "      TArrayS dummy;" << endl;
+    for (int i=0; i<fPixelsIdx.GetSize(); i++)
+        out << "      dummy[" << i << "]=" << ((TArrayS)fPixelsIdx)[i] << ";" << endl;
+    out << "      " << GetUniqueName() << ".SetPixels(dummy);" << endl;
+    out << "   }" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelCalc.h	(revision 3781)
@@ -0,0 +1,69 @@
+#ifndef MARS_MBlindPixelCalc
+#define MARS_MBlindPixelCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MGeomCam;
+class MPedestal;
+class MCerPhotEvt;
+class MBlindPixels;
+class MPedestalCam;
+
+class MBlindPixelCalc : public MTask
+{
+private:
+    MCerPhotEvt  *fEvt;     //!
+    MBlindPixels *fPixels;  //!
+    MGeomCam     *fGeomCam; //!
+    MPedestalCam *fPed;     //!
+
+    TArrayS fPixelsIdx;  // Pixel Indices for blind pixels, which are entered by the user.
+
+    Byte_t fFlags;       // flag for the method which is used
+
+    enum
+    {
+        kUseInterpolation = 1,
+        kUseCentralPixel  = 2,
+        kUseBlindPixels   = 3
+    };
+
+    static Double_t Sqr(Double_t x) { return x*x; }
+
+    void Interpolate() const;
+    void Unmap() const;
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MBlindPixelCalc(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 SetUseBlindPixels(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseBlindPixels) : CLRBIT(fFlags, kUseBlindPixels);
+    }
+
+    void SetPixelIndices(const TArrayS &pix) { fPixelsIdx = pix; }
+    virtual Bool_t ReInit(MParList *pList);
+
+    ClassDef(MBlindPixelCalc, 1) // task to deal with hot spots (star, broken pixels, etc)
+}; 
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.cc	(revision 3781)
@@ -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 express
+! * or implied warranty.
+! *
+!
+!
+!   Author(s): Oscar Blanch    12/2001 <mailto:blanch@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MBlindPixel                                                             //
+//                                                                         //
+// If you want to exclude pixels from the analysis (eg. hillas parameter   //
+// calculation) you can use this container to switch off the pixels by Id  //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MBlindPixels.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MBlindPixels);
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBlindPixels::MBlindPixels(const char *name, const char *title) : fPixels(577)
+
+{
+    fName  = name  ? name  : "MBlindPixels";
+    fTitle = title ? title : "Container which have a list of blind pixels";
+}
+
+// -------------------------------------------------------------------------
+//
+// If you don't want to use pixel with Id id call
+//    SetPixelBlind(id, kTRUE)
+// otherwise
+//    SetPixelBlind(id, kFALSE)
+//
+void MBlindPixels::SetPixelBlind(UShort_t id, Bool_t val)
+{
+    fPixels.AddAt(val, id);
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixels.h	(revision 3781)
@@ -0,0 +1,35 @@
+#ifndef MARS_MBlindPixels
+#define MARS_MBlindPixels
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include <TArrayC.h>
+#endif
+
+class MBlindPixels : public MParContainer
+{
+private:
+    TArrayC fPixels; // Boolean value for every pixel 0=on, 1=blind
+
+public:
+    MBlindPixels(const char *name=NULL, const char *title=NULL);
+
+    void SetPixelBlind(UShort_t id, Bool_t val=kTRUE);
+    void AdoptPixels(Char_t pixels[577]) { fPixels.Adopt(577, pixels); }
+
+    void AdoptPixels(const TArrayC &pixels) { fPixels = pixels; }
+
+    void Clear(Option_t *o="")  { fPixels.Reset(); }
+
+    Bool_t IsBlind(UShort_t id) const { return fPixels.GetSize() && ((TArrayC)fPixels)[id]; }
+
+    void InitSize(UShort_t i) { fPixels.Set(i); }
+
+    ClassDef(MBlindPixels, 1) // container to store blind pixels
+}; 
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.cc	(revision 3781)
@@ -0,0 +1,671 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!   Author(s): Nadia Tonello   02/2004 <mailto:tonello@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MBlindPixelsCalc2
+//
+//  NT:: WARNING: This class will change soon to fit into mbadpixels!!
+//  It does all MBlindPixelCalc did, plus check the pedestal Rms 
+//  to define bad pixels.
+// 
+//  This is the specific image cleaning for a list of pixels. This task
+//  sets the pixels listed in fPixelsIdx to unused so they should not be
+//  used for analysis (eg calculation of hillas parameters).
+//
+//  NT::You can use MBlindPixelsCalc2::SetCheckPedestalRms to see which
+//  pixels to blind. If the PedestalRms in one pixel is more than 
+//  3 times the mean or less than 1/3 the mean, they are set as blind.
+//
+//  You can use MBlindPixelsCalc2::SetUseInterpolation to replace the
+//  blind pixels by the average of its neighbors instead of unmapping
+//  them. If you want to include the central pixel use
+//  MBlindPixelsCalc2::SetUseCentralPixel.
+//  NT:: The interpolation will be done only if there are at least
+//  3 non-blind pixels. 
+//
+//  Example:
+//     MBadPixelCalc2 blind;
+//     blind.SetCheckPedestalRms();
+//     blind.SetUseInterpolation();
+//
+//  If you do not use SetUseInterpolation(), the pixels selected with 
+//  SetCheckPedestalRms will be Unmapped and not used for the image
+//  analysis.
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   [MBlindPixels]
+//
+//  Output Containers:
+//   MCerPhotEvt
+//   MBlindPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBlindPixelsCalc2.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MBlindPixels.h"
+
+#include "MMcRunHeader.hxx"
+
+ClassImp(MBlindPixelsCalc2);
+
+using namespace std;
+
+static const TString gsDefName  = "MBlindPixelsCalc2";
+static const TString gsDefTitle = "Find hot spots (star, broken pixels, etc)";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MBlindPixelsCalc2::MBlindPixelsCalc2(const char *name, const char *title)
+  : fFlags(0), fErrors(3)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Try to find or create MBlindPixels in parameter list.
+//  - get the MCerPhotEvt from the parlist (abort if missing)
+//
+Int_t MBlindPixelsCalc2::PreProcess (MParList *pList)
+{
+    if (TESTBIT(fFlags, kUseBlindPixels))
+      fPixels = (MBlindPixels*)pList->FindObject(AddSerialNumber("MBlindPixels"));
+    else
+        fPixels = (MBlindPixels*)pList->FindCreateObj(AddSerialNumber("MBlindPixels"));
+
+    if (!fPixels)
+        {*fLog << err << dbginf << "Try to remove  -SetUseBlindPixels-  from the task list to go on" << endl; 
+    return kFALSE;}
+
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber("MPedPhotCam"));
+    if (!fPed)
+    {
+        *fLog << err << dbginf << "MPedPhotCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam)
+        *fLog << warn << dbginf << "No camera geometry available... can't use interpolation." << endl;
+
+    const UShort_t size = fPixelsIdx.GetSize();
+    if (size == 0)
+    {
+        if (!pList->FindObject("MMcRunHeader") && !fPixels)
+        {
+            *fLog << warn << "Warning - Neither blind pixels are given nor a MMcRunHeader was found... removing MBlindPixelsCalc2 from list." << endl;
+            return kSKIP;
+        }
+        return kTRUE;
+    }
+
+    // Set as blind pixels the global blind pixels, which are given
+    // through the macros
+
+    UShort_t numids = fPixelsIdx.GetSize();
+
+    for(Int_t i = 0; i<numids; i++)
+	fPixels->SetPixelBlind(fPixelsIdx[i]);
+
+
+   memset(fErrors.GetArray(), 0, sizeof(Char_t)*fErrors.GetSize());
+
+
+    fErrors[0]= 0;
+    fErrors[1]= 0;
+    fErrors[2]= 0;
+
+    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 MBlindPixelsCalc2::Interpolate() const
+{
+    const UShort_t entries = fGeomCam->GetNumPixels();
+
+    //
+    // Create arrays
+    //
+    Double_t *nphot  = new Double_t[entries];
+    Double_t *perr   = new Double_t[entries];
+ 
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (!fPixels->IsBlind(i))
+            continue;
+
+        //
+        // Get a pointer to this pixel. If it is not yet existing
+        // create a new entry for this pixel in MCerPhotEvt
+        //
+
+	MCerPhotPix *pix = fEvt->GetPixById(i);
+        if (!pix)
+            pix = fEvt->AddPixel(i, 0, 0);
+
+        //
+        // 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 (fPixels->IsBlind(nidx))
+                continue;
+
+            //
+            // Check whether the neighbor has a signal stored
+            //
+            const MCerPhotPix *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++;
+        }
+
+        //
+	// 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));
+ 
+
+	// 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 < 3) 
+	  { pix->SetPixelUnmapped();
+	  //	    pix->Set(nphot[i], perr[i]);
+ 	    continue;
+	  }
+
+	    pix->Set(nphot[i], perr[i]);
+    }
+    //
+    // Delete the intermediat arrays
+    //
+    delete nphot;
+    delete perr;
+}
+
+// --------------------------------------------------------------------------
+//
+
+void MBlindPixelsCalc2::InterpolatePedestals() const
+{
+  const Int_t entries = fPed->GetSize();
+  Double_t *ped    = new Double_t[entries];
+  Double_t *pedrms = new Double_t[entries];
+  
+  //
+  // Loop over all pixels
+  //
+  for (UShort_t i=0; i<entries; i++)
+    {
+      //
+      // Check whether pixel with idx i is blind
+      //
+      if (!fPixels->IsBlind(i))
+	continue;
+      
+      //
+      // Get the corresponding geometry and pedestal
+      //
+      const MGeomPix &gpix = (*fGeomCam)[i];
+      const MPedPhotPix &ppix = (*fPed)[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();
+      pedrms[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;
+      pedrms[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 (fPixels->IsBlind(nidx))
+	    continue;
+	  
+	  //
+	  // Get the geometry for the neighbor
+	  //
+	  const Double_t nratio = fGeomCam->GetPixRatio(nidx);
+	  MPedPhotPix &nppix = (*fPed)[nidx];
+	  
+	  //
+	  //The error is calculated as the quadratic sum of the errors
+	  //
+	  ped[i]    += (nratio*nppix.GetMean());
+	  pedrms[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 3 
+      
+      if (num < 3) 
+	{ 	
+	  MCerPhotPix *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);
+      pedrms[i] = TMath::Sqrt(pedrms[i]/(num*ratio));
+      
+     (*fPed)[i].Set(ped[i], pedrms[i]);
+    }
+  
+  //
+  // Delete the arrays
+  //
+  delete ped;
+  delete pedrms;
+  
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Removes all blind pixels from the analysis by setting their state
+//  to unmapped.
+//
+void MBlindPixelsCalc2::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++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        if (fPixels->IsBlind(pix.GetPixId()))
+	      pix.SetPixelUnmapped();
+    }
+}
+
+// --------------------------------------------------------------------------
+// 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 MBlindPixelsCalc2::CheckPedestalRms() 
+
+{
+  const Int_t entries = fPed->GetSize();
+  Int_t pixtoblind = 0;
+  Int_t pixin = 0;
+  Int_t pixout = 0;
+
+  Float_t meanPedRms =0.;
+  Float_t meanPedRmsout = 0.;
+  Float_t meanPedRms2 = 0.;
+  Float_t meanPedRmsout2 = 0.;
+
+ for (Int_t i=0; i<entries; i++)
+    {
+      //
+      // get pixel as entry from list
+      // 
+      const MPedPhotPix &ppix = (*fPed)[i];
+      const Double_t nratio = fGeomCam->GetPixRatioSqrt(i);
+      const Double_t pixPedRms = ppix.GetRms();
+     
+      //Calculate the corrected means:
+      
+      if (nratio == 1 )
+	{
+	  if(  pixPedRms >0. &&  pixPedRms <200. )
+	  {meanPedRms += pixPedRms;
+	  pixin++;}
+	}
+      else 
+	{
+	  if(  pixPedRms >0. &&  pixPedRms <500. )
+	  {meanPedRmsout += pixPedRms;
+	  pixout++;}
+	}
+    }
+ 
+      //if no pixel has a minimum signal, return
+ if( pixin==0 || pixout==0 )
+   {fErrors[1]++;          //no valid Pedestals Rms
+   return kFALSE;
+   } 
+ 
+ meanPedRms =  meanPedRms / pixin ;
+ meanPedRmsout =  meanPedRmsout / pixout ;
+
+ if (  meanPedRms == 0. ||   meanPedRmsout ==0.)
+   {fErrors[1]++;         //no valid Pedestals Rms
+   return kFALSE;
+   }
+ 
+ pixin  = 0;
+ pixout = 0;
+
+ for (Int_t i=0; i<entries; i++)
+   {
+     //
+     // get pixel as entry from list
+     // 
+     const MPedPhotPix &ppix = (*fPed)[i];
+     const Double_t nratio = fGeomCam->GetPixRatioSqrt(i);
+     const Double_t pixPedRms = ppix.GetRms();
+     
+     //Calculate the corrected means:
+     
+     if (nratio == 1)
+       {if (pixPedRms > 0.5 * meanPedRms  && pixPedRms < 1.5 * meanPedRms)  
+	 {meanPedRms2 += pixPedRms;
+	 pixin++;}
+       }
+     else 
+       {if (pixPedRms > 0.5 * meanPedRmsout  && pixPedRms < 1.5 * meanPedRmsout)  
+	 {meanPedRmsout2 += pixPedRms;
+	 pixout++;}
+       }
+   }
+     
+      //if no pixel has a minimum signal, return
+ if( pixin==0 || pixout==0 )
+   {fErrors[1]++;            //no valid Pedestals Rms
+   return kFALSE;} 
+ 
+ meanPedRms =  meanPedRms2 / pixin ;
+ meanPedRmsout =  meanPedRmsout2 / pixout ;
+
+ //Blind the Bad Pixels
+ for (Int_t i=0; i<entries; i++)
+   {
+     const MPedPhotPix &ppix = (*fPed)[i];
+     const Float_t nratio = fGeomCam->GetPixRatioSqrt(i);
+     const Double_t pixPedRms = ppix.GetRms();
+     
+     if (nratio == 1)	
+       { if (pixPedRms > 3.* meanPedRms || pixPedRms <= meanPedRms/3.)
+	 { fPixels->SetPixelBlind(i); 
+	 pixtoblind++;}
+       }
+     else
+       { if (pixPedRms > 3.* meanPedRmsout || pixPedRms <= meanPedRmsout/3.)
+	 { fPixels->SetPixelBlind(i); 
+	 pixtoblind++; }
+       }
+   }
+ 
+ // Check if the number of pixels to blind is > 60% of total number of pixels
+ // 
+ if (pixtoblind>0.6*entries)
+   { fErrors[2]++;
+   return kFALSE; }
+ 
+ 
+ return kTRUE;
+ 
+}
+
+// --------------------------------------------------------------------------
+//
+// Treat the blind pixels
+//
+Int_t MBlindPixelsCalc2::Process()
+{
+   if (TESTBIT(fFlags, kCheckPedestalRms))
+     {
+       // if the number of blind pixels is too high, do not interpolate
+       if (CheckPedestalRms()== kFALSE) 
+	   return kTRUE;
+       else
+	 {if (TESTBIT(fFlags, kUseInterpolation))
+	   InterpolatePedestals();	         
+	 } 
+     }
+
+   if (TESTBIT(fFlags, kUseInterpolation) && fGeomCam)
+     {   Interpolate();
+     } 
+   else
+     { Unmap();
+     } 
+     fErrors[0]++;
+   return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  - Check whether pixels to disable are available. If pixels are
+//    given by the user nothing more is done.
+//
+Bool_t MBlindPixelsCalc2::ReInit(MParList *pList)
+{
+    if (TESTBIT(fFlags, kUseBlindPixels))
+        return kTRUE;
+
+    //
+    // If pixels are given by the user, we are already done
+    //
+    if (fPixelsIdx.GetSize() > 0)
+        return kTRUE;
+
+    //
+    // Delete the old array holding the blind pixels for the last file
+    //
+    fPixels->Clear();
+
+    if (!fGeomCam->InheritsFrom("MGeomCamMagic"))
+    {
+        *fLog << warn << "MBlindPixelsCalc2::ReInit: Warning - Starfield only implemented for Magic standard Camera... no action." << endl;
+        return kTRUE;
+    }
+   return kTRUE;
+}
+
+void MBlindPixelsCalc2::StreamPrimitive(ofstream &out) const
+{
+    out << "   MBlindPixelsCalc2 " << GetUniqueName();
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << "(\"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+        out <<")";
+    }
+    out << ";" << endl;
+
+    if (TESTBIT(fFlags, kUseInterpolation))
+        out << "   " << GetUniqueName() << ".SetUseInterpolation();" << endl;
+    if (TESTBIT(fFlags, kUseCentralPixel))
+        out << "   " << GetUniqueName() << ".SetUseCentralPixel();" << endl;
+    if (TESTBIT(fFlags, kCheckPedestalRms))
+        out << "   " << GetUniqueName() << ".SetCheckPedestalRms();" << endl;
+
+    if (fPixelsIdx.GetSize()==0)
+        return;
+
+    out << "   {" << endl;
+    out << "      TArrayS dummy;" << endl;
+    for (int i=0; i<fPixelsIdx.GetSize(); i++)
+        out << "      dummy[" << i << "]=" << ((TArrayS)fPixelsIdx)[i] << ";" << endl;
+    out << "      " << GetUniqueName() << ".SetPixels(dummy);" << endl;
+    out << "   }" << endl;
+}
+
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess. Later (having
+//  millions of events) we may want to improve the output.
+//
+void MBlindPixelsCalc2::PrintSkipped(int i, const char *str) const
+{
+    *fLog << " " << setw(7) << fErrors[i] << " (";
+    *fLog << setw(3) << (int)(100.*fErrors[i]/GetNumExecutions());
+    *fLog << "%) Evts skipped due to: " << str << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the calculation. The percentage
+//  is calculated with respect to the number of executions of this task.
+//
+Int_t MBlindPixelsCalc2::PostProcess()
+{
+    if (GetNumExecutions()==0)
+        return kTRUE;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+
+    // Number of events where the computation of the mean pedestal Rms failed 
+    // On these events no blind pixels have been selected
+
+    if (TESTBIT(fFlags, kCheckPedestalRms))
+    PrintSkipped(1, "Big fluctuations in Pedestal Rms, no CHECK");
+
+    // Number of events with too many bad pixels have been found
+    // On these events, no interpolation has been applied
+
+    if (TESTBIT(fFlags, kUseInterpolation))
+    PrintSkipped(2, " >60% of pixels are bad, no INTERPOLATION");
+
+    //Number of events that have been  succesfully checked and corrected
+
+    *fLog << " " << (int)fErrors[0] << " (" << (int)(100.*fErrors[0]/GetNumExecutions()) << "%) Evts well treated!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MBlindPixelsCalc2.h	(revision 3781)
@@ -0,0 +1,95 @@
+#ifndef MARS_MBlindPixelsCalc2
+#define MARS_MBlindPixelsCalc2
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+#ifndef ROOT_TArrayL
+#include <TArrayL.h>
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+class MBlindPixels;
+
+class MPedPhotCam;
+
+class MBlindPixelsCalc2 : public MTask
+{
+private:
+    MCerPhotEvt  *fEvt;     //!
+    MBlindPixels *fPixels;  //!
+    MGeomCam     *fGeomCam; //!
+    MPedPhotCam  *fPed;     //!
+
+    TArrayS fPixelsIdx;  // Pixel Indices for blind pixels, which are entered by the user.
+    Byte_t fFlags;       // flag for the method which is used
+
+    enum
+    {
+        kUseInterpolation = 1,
+        kUseCentralPixel  = 2,
+	kCheckPedestalRms = 3,
+        kUseBlindPixels   = 4
+    };
+
+ 
+    static Double_t Pow2(Double_t x) { return x*x; }
+
+    void Interpolate() const;
+    void InterpolatePedestals() const;
+    void Unmap() const;
+    Bool_t CheckPedestalRms() ;
+
+
+    void PrintSkipped(int i, const char *str) const;
+
+    void StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    TArrayL  fErrors;     
+
+public:
+
+    MBlindPixelsCalc2(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 SetCheckPedestalRms(Bool_t b=kTRUE) 
+   {
+        b ? SETBIT(fFlags,kCheckPedestalRms) : CLRBIT(fFlags, kCheckPedestalRms);
+    }
+    void SetUseBlindPixels(Bool_t b=kTRUE)
+    {
+        b ? SETBIT(fFlags, kUseBlindPixels) : CLRBIT(fFlags, kUseBlindPixels);
+    }
+
+    void SetPixelIndices(const TArrayS &pix) { fPixelsIdx = pix; }
+
+    virtual Bool_t ReInit(MParList *pList);
+
+    ClassDef(MBlindPixelsCalc2, 1) // (temp!)task to deal with hot spots (star, broken pixels, etc) 
+}; 
+
+#endif
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1FindSupercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadONOFF.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PadSchweizer.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.cc	(revision 3781)
@@ -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  03/2003 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//  MCT1PointingCorrCalc                                                   //
+//                                                                         //
+//  This is a task to do the CT1 pointing correction                       //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#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)
+{
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the pointing correction
+//
+// the parametrization is for Mkn421 2001 data (Daniel Kranich)
+// 
+Int_t MCT1PointingCorrCalc::Process()
+{
+   // fhourangle is the hour angle [degrees]
+   // (cx, cy) is the source position in the camera [mm]
+   //
+   Float_t fhourangle = fHourAngle->GetVal();
+
+   //*fLog << "MCT1PointingCorrCalc::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 << "MCT1PointingCorrCal::Process; fhourangle, cx, cy, fMm2Deg = "
+   //      << fhourangle << ",  " << cx << ",  " << cy << ",  " 
+   //      << fMm2Deg << endl;
+
+   fSrcPos->SetReadyToSave();
+
+   return kTRUE;
+}
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1PointingCorrCalc.h	(revision 3781)
@@ -0,0 +1,51 @@
+#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
+{
+private:
+
+    MSrcPosCam   *fSrcPos;
+    TString       fSrcName;
+    MParameterD  *fHourAngle;
+
+    Float_t       fMm2Deg;
+
+public:
+    MCT1PointingCorrCalc(const char *srcname="MSrcPosCam",
+                         const char *name=NULL, const char *title=NULL);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    ClassDef(MCT1PointingCorrCalc, 0)   // Task to do the CT1 pointing correction for Mkn421 2001 data
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1Supercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCT1SupercutsCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCameraData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCameraData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCameraData.cc	(revision 3781)
@@ -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): Thomas Bretz, 10/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCameraData
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCameraData.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+#include "MGeomCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MSigmabar.h"
+
+ClassImp(MCameraData);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MCerPhotPix object for each pixel in the event
+//
+MCameraData::MCameraData(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCameraData";
+    fTitle = title ? title : "Photons/PedRMS Information";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+}
+*/
+
+void MCameraData::CalcCleaningLevel(const MCerPhotEvt &evt, const MPedPhotCam &cam,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    const Int_t entries = evt.GetNumPixels();
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    // 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MCerPhotPix &pix = evt[i];
+
+        const Int_t idx = pix.GetPixId();
+        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;
+    }
+}
+
+void MCameraData::CalcCleaningLevel(const MCerPhotEvt &evt, const MSigmabar &sgb,
+                                    const MGeomCam &geom)
+{
+    CalcCleaningLevel(evt, sgb.GetSigmabarInner(), geom);
+}
+
+void MCameraData::CalcCleaningLevel(const MCerPhotEvt &evt, Double_t noise,
+                                    const MGeomCam &geom)
+{
+    const Int_t n = geom.GetNumPixels();
+
+    fData.Set(n);
+    fData.Reset();
+
+    fValidity.Set(n);
+    fValidity.Reset();
+
+    if (noise<=0)
+        return;
+
+    const Int_t entries = evt.GetNumPixels();
+
+    //
+    // check the number of all pixels against the noise level and
+    // set them to 'unused' state if necessary
+    // 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MCerPhotPix &pix = evt[i];
+
+        const Int_t idx = pix.GetPixId();
+
+        //
+	// 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;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+//
+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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCameraData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCameraData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCameraData.h	(revision 3781)
@@ -0,0 +1,57 @@
+#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 MCerPhotEvt;
+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 MCerPhotEvt &evt, const MPedPhotCam &fCam,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel(const MCerPhotEvt &evt, const MSigmabar &sgb,
+                           const MGeomCam &geom);
+    void CalcCleaningLevel(const MCerPhotEvt &evt, Double_t noise,
+                           const MGeomCam &geom);
+/*
+    void Calc(const MCerPhotEvt &evt, const MGeomCam &geom)
+    {
+        CalcCleaningLevel(evt, 1, geom);
+    }
+ */
+    const TArrayD &GetData() const { return fData; }
+    const TArrayC &GetValidity() const  { return fValidity; }
+
+    Double_t operator[](int i) { return fData[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(MCameraData, 2)    // class for an event containing cerenkov photons
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.cc	(revision 3781)
@@ -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): Thomas Bretz  12/2000 <mailto:tbretz@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//   MCerPhotAnal                                                           //
+//                                                                          //
+//   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, MPedesdtalCam                                             //
+//                                                                          //
+//  Output Containers:                                                      //
+//   MCerPhotEvt                                                            //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MCerPhotAnal.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"       // MRawEvtData::GetNumPixels
+#include "MCerPhotEvt.h"
+#include "MPedestalPix.h"
+#include "MPedestalCam.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MCerPhotAnal);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCerPhotAnal::MCerPhotAnal(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCerPhotAnal";
+    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
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MCerPhotEvt
+//
+Int_t MCerPhotAnal::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)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MCerPhotAnal::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 MCerPhotEvt container.
+//
+Int_t MCerPhotAnal::Process()
+{
+    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());
+
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    while (pixel.Next())
+    {
+	Byte_t *ptr = pixel.GetHiGainSamples();
+	const Byte_t *end = ptr + fRawEvt->GetNumHiGainSamples();
+	const Byte_t *limit = end - 5;
+	
+	Int_t sum=0;
+	Int_t sumpeak=0;
+	Int_t sumlocal =0;
+	Int_t slice=0;
+	Int_t slicelocal=0;
+
+	do
+        {
+            sumlocal = 0;
+            for (Int_t i = 0; i<5;i++)
+                sumlocal += *(ptr+i);
+
+            if (sumpeak < sumlocal)
+            {
+                slice=slicelocal;
+                sumpeak = sumlocal;
+            }
+
+            slicelocal++;
+	    sum += *ptr;
+        } while (++ptr != limit);
+
+        do sum += *ptr;
+        while (++ptr != end);
+
+        Float_t pedes = (Float_t)(sum-sumpeak)/(fRawEvt->GetNumHiGainSamples()-5);
+        Float_t nphot = (Float_t)sumpeak - 5.0*pedes;
+
+        Float_t sigmaped=0;
+
+        slicelocal=0;
+        sumlocal = 0;
+
+	ptr = pixel.GetHiGainSamples();
+        do
+        {
+            if (slicelocal==slice)
+                ptr += 4;
+            else
+            {
+                sumlocal = *ptr;
+
+                const Float_t d = (Float_t)sumlocal-pedes;
+                sigmaped += d*d;
+            }
+            slicelocal++;
+	}
+        while (++ptr != end);
+
+	sigmaped /= (fRawEvt->GetNumHiGainSamples()-5);
+	sigmaped = sqrt((float)sumlocal);
+
+	const UInt_t pixid = pixel.GetPixelId();
+
+        fCerPhotEvt->AddPixel(pixid, nphot, sigmaped/2.236);
+
+        if (fPedestals)
+            (*fPedestals)[pixid].Set(pedes, sigmaped);
+
+        /*
+         ped.SetPedestalRms(sigmaped/sqrt(fRawEvt->GetNumHiGainSamples()-5.),
+                            sigmaped/sqrt(2.*(fRawEvt->GetNumHiGainSamples()-5)));
+                            */
+        // FIXME! Handling of Lo Gains is missing!
+    }
+
+    fCerPhotEvt->FixSize();
+    fCerPhotEvt->SetReadyToSave();
+
+    if (fPedestals)
+        fPedestals->SetReadyToSave();
+
+    return kTRUE;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal.h	(revision 3781)
@@ -0,0 +1,39 @@
+#ifndef MARS_MCerPhotAnal
+#define MARS_MCerPhotAnal
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCerPhotAnal                                                            //
+//                                                                         //
+// Integrates the time slices of one pixel and substracts the pedestal     //
+// (offset) value                                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MPedestalCam;
+class MCerPhotEvt;
+class MRawRunHeader;
+
+class MCerPhotAnal : 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
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+ 
+public:
+    MCerPhotAnal(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MCerPhotAnal, 0)   // Task to calculate cerenkov photons from raw data
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.cc	(revision 3781)
@@ -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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCerPhotAnal2
+//
+//   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, MPedPhotCam
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MCerPhotAnal2.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtData.h"       // MRawEvtData::GetNumPixels
+#include "MCerPhotEvt.h"
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+#include "MRawEvtPixelIter.h"
+
+ClassImp(MCerPhotAnal2);
+
+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.
+//
+MCerPhotAnal2::MCerPhotAnal2(Byte_t b, Byte_t a, const char *name, const char *title)
+    : fBefore(b), fAfter(a)
+{
+    fName  = name  ? name  : "MCerPhotAnal2";
+    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
+//  - MPedPhotCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//  - MCerPhotEvt
+//
+Int_t MCerPhotAnal2::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 = (MCerPhotEvt*)pList->FindCreateObj("MCerPhotEvt");
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+Bool_t MCerPhotAnal2::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 = (MPedPhotCam*)pList->FindCreateObj("MPedPhotCam");
+    if (runheader && !fPedestals)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MCerPhotEvt container.
+//
+Int_t MCerPhotAnal2::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 MCerPhotAnal2::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-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotAnal2.h	(revision 3781)
@@ -0,0 +1,46 @@
+#ifndef MARS_MCerPhotAnal2
+#define MARS_MCerPhotAnal2
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCerPhotAnal2                                                            //
+//                                                                         //
+// Integrates the time slices of one pixel and substracts the pedestal     //
+// (offset) value                                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MPedPhotCam;
+class MCerPhotEvt;
+class MRawRunHeader;
+
+class MCerPhotAnal2 : public MTask
+{
+private:
+    MPedPhotCam   *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
+
+    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:
+    MCerPhotAnal2(Byte_t b=2, Byte_t a=5, const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MCerPhotAnal2, 0)   // Task to calculate cerenkov photons from raw data
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.cc	(revision 3781)
@@ -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): 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCerPhotCalc
+//
+//   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:
+//   MRawEvtData
+//   MPedestalCam
+//   [MRawRunHeader]
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCerPhotCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.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(MCerPhotCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MCerPhotCalc::MCerPhotCalc(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCerPhotCalc";
+    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 MCerPhotCalc::PreProcess(MParList *pList)
+{
+    fRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRunHeader)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedestals = (MPedestalCam*)pList->FindCreateObj(AddSerialNumber("MPedestalCam"));
+    if (!fPedestals)
+    {
+        *fLog << err << "MPedestalCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+        return kFALSE;
+
+    // Calculate sum and quadratic sum of weights:
+    fSumWeights = 0;
+    fSumQuadWeights = 0;
+    for (Int_t i=0; i<fWeight.GetSize(); i++)
+      {
+	fSumWeights += fWeight[i];
+	fSumQuadWeights += fWeight[i]*fWeight[i];
+      }
+
+    fSumQuadWeights = sqrt(fSumQuadWeights);
+
+    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 MCerPhotCalc::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;
+    }
+
+    if (!runheader->IsMonteCarloRun())
+        return kTRUE;
+
+    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;
+
+    ScalePedestals();
+
+    return kTRUE;
+}
+
+void MCerPhotCalc::ScalePedestals()
+{
+    const Int_t n = fPedestals->GetSize();
+
+    for (int idx=0; idx<n; idx++)
+    {
+        MPedestalPix &ped = (*fPedestals)[idx];
+
+	// This converts the pedestal info contained in ped  from the pedestal 
+	// of each FADC slice to the pedesal of the pixel signal (depends on
+	// how many FADC slices are added up).
+
+        const Double_t offset = fEnableFix ? ped.GetPedestal()-0.5 : ped.GetPedestal();
+
+        ped.Set(offset*fSumWeights, ped.GetPedestalRms()*fSumQuadWeights);
+    }
+
+    fPedestals->SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate the integral of the FADC time slices and store them as a new
+// pixel in the MCerPhotEvt container.
+//
+Int_t MCerPhotCalc::Process()
+{
+    //fCerPhotEvt->InitSize(fRawEvt->GetNumPixels());
+
+//    if (fIsMcFile)
+//        ScalePedestals();
+
+    const Int_t n = fWeight.GetSize();
+
+    MRawEvtPixelIter pixel(fRawEvt);
+
+    Int_t saturatedpixels = 0;
+
+    while (pixel.Next())
+    {
+        const UInt_t idx = pixel.GetPixelId();
+
+        MPedestalPix &ped = (*fPedestals)[idx];
+
+        //
+        // Calculate pixel signal unless it has all FADC slices empty:
+        //
+        Byte_t *ptr = pixel.GetHiGainSamples();
+
+        Int_t i;
+        Double_t nphot = 0;
+        for (i=0; i<n; i++)
+        {
+            if (ptr[i]==0xff)
+                break;
+            nphot += ptr[i]*fWeight[i];
+        }
+
+	Bool_t saturatedlg = kFALSE;
+
+        if (i<n)
+        {
+	    nphot = 0;
+
+            ptr = pixel.GetLoGainSamples();
+            if (ptr==NULL)
+            {
+                *fLog << warn << "WARNING - Pixel #" << idx << " saturated but has no lo gains... skipping!" << endl;
+                return kCONTINUE;
+            }
+
+            for (i=0; i<n; i++)
+            {
+                if (ptr[i]==0xff)
+                    saturatedlg = kTRUE;
+
+                nphot += ptr[i]*fWeight[i];
+            }
+
+            nphot -= ped.GetPedestal();
+            nphot *= 10;
+        }
+        else
+            nphot -= ped.GetPedestal();
+
+        fCerPhotEvt->AddPixel(idx, nphot, 0);
+
+	if (saturatedlg)
+	  saturatedpixels++;
+    }
+
+    if (saturatedpixels>0)
+        *fLog << warn << "WARNING: " << saturatedpixels << " pixel(s) had saturating low gains..." << endl;
+
+    fCerPhotEvt->FixSize();
+    fCerPhotEvt->SetReadyToSave();
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set default values for the number of slices and weights:
+//
+void MCerPhotCalc::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-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotCalc.h	(revision 3781)
@@ -0,0 +1,57 @@
+#ifndef MARS_MCerPhotCalc
+#define MARS_MCerPhotCalc
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCerPhotCalc                                                            //
+//                                                                         //
+// 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 MCerPhotCalc : 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         fSumQuadWeights;
+    Float_t         fSumWeights;
+
+    void SetDefaultWeights();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    Bool_t ReInit(MParList *pList);
+    void ScalePedestals();
+
+public:
+    MCerPhotCalc(const char *name=NULL, const char *title=NULL);
+
+    // FIXME: The array size should be checked!
+    void   SetWeights(const TArrayF &w) { fWeight = w; }
+
+    ClassDef(MCerPhotCalc, 0)   // Task to calculate cerenkov photons from raw data
+};
+ 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.cc	(revision 3781)
@@ -0,0 +1,466 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//            
+// MCerPhotEvt
+//
+// NOTE: This container is NOT ment for I/O. Write it to a file on your own
+//       risk!
+//
+// Class Version 2:
+// ----------------
+//  - added fLut to accelerate GetPixById a lot
+//            
+// Class Version 1:
+// ----------------
+//  - first version
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCerPhotEvt.h"
+
+#include <math.h>
+#include <limits.h>
+#include <fstream>
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MCerPhotEvt);
+ClassImp(MCerPhotEvtIter);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Creates a MCerPhotPix object for each pixel in the event
+//
+MCerPhotEvt::MCerPhotEvt(const char *name, const char *title) : fNumPixels(0)
+{
+    fName  = name  ? name  : "MCerPhotEvt";
+    fTitle = title ? title : "(Number of Photon)-Event Information";
+
+    fPixels = new TClonesArray("MCerPhotPix", 0);
+}
+
+// --------------------------------------------------------------------------
+//
+// This is not yet implemented like it should.
+//
+/*
+void MCerPhotEvt::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 MCerPhotEvt::Reset()
+{
+    fNumPixels =  0;
+    fMaxIndex  = -1;
+    fLut.Set(0);
+    // fPixels->Delete();
+}
+
+void MCerPhotEvt::FixSize()
+{
+    fLut.Set(fMaxIndex+1);
+
+    if (fPixels->GetEntriesFast() == (Int_t)fNumPixels)
+        return;
+
+    fPixels->ExpandCreateFast(fNumPixels);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Dump the cerenkov photon event to *fLog
+//
+void MCerPhotEvt::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();
+}
+
+// --------------------------------------------------------------------------
+//
+// Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MCerPhotEvt::IsPixelExisting(Int_t id) const
+{
+    return GetPixById(id) ? kTRUE : kFALSE;
+} 
+
+// --------------------------------------------------------------------------
+//
+//   Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MCerPhotEvt::IsPixelUsed(Int_t id) const
+{
+    const MCerPhotPix *pix = GetPixById(id);
+    return pix ? pix->IsPixelUsed() : kFALSE;
+} 
+
+// --------------------------------------------------------------------------
+//
+//   Checks if in the pixel list is an entry with pixel id
+//
+Bool_t MCerPhotEvt::IsPixelCore(Int_t id) const
+{
+    const MCerPhotPix *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 MCerPhotEvt::GetNumPhotonsMin(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 MCerPhotPix &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(id);
+
+        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 MCerPhotEvt::GetNumPhotonsMax(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 MCerPhotPix &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(id);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the minimum ratio of photons/error
+//
+Float_t MCerPhotEvt::GetRatioMin(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return -5.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MCerPhotPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= TMath::Sqrt(geom->GetPixRatio(pix.GetPixId()));
+
+        if (testval < minval)
+            minval = testval;
+    }
+
+    return minval;
+}
+
+// --------------------------------------------------------------------------
+//
+// get the maximum ratio of photons/error
+//
+Float_t MCerPhotEvt::GetRatioMax(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return -5.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MCerPhotPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetNumPhotons()/pix.GetErrorPhot();
+        if (geom)
+            testval *= TMath::Sqrt(geom->GetPixRatio(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 MCerPhotEvt::GetErrorPhotMin(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return 50.;
+
+    Float_t minval = FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MCerPhotPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(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 MCerPhotEvt::GetErrorPhotMax(const MGeomCam *geom) const
+{
+    if (fNumPixels <= 0)
+        return 50.;
+
+    Float_t maxval = -FLT_MAX;
+
+    for (UInt_t i=0; i<fNumPixels; i++)
+    {
+        const MCerPhotPix &pix = (*this)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        Float_t testval = pix.GetErrorPhot();
+
+        if (geom)
+            testval *= geom->GetPixRatio(pix.GetPixId());
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+
+void MCerPhotEvt::RemoveUnusedPixels()
+{
+    TIter Next(fPixels);
+    MCerPhotPix *pix = NULL;
+
+    while ((pix=(MCerPhotPix*)Next()))
+        if (!pix->IsPixelUsed())
+            fPixels->Remove(pix);
+
+    fPixels->Compress();
+    fNumPixels=fPixels->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+MCerPhotPix *MCerPhotEvt::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 : (MCerPhotPix*)(fPixels->UncheckedAt(fLut[idx]));
+    }
+
+    TIter Next(fPixels);
+    MCerPhotPix *pix = NULL;
+
+    while ((pix=(MCerPhotPix*)Next()))
+        if (pix->GetPixId()==idx)
+            return pix;
+
+    return NULL;
+}
+
+MCerPhotPix *MCerPhotEvt::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++]) MCerPhotPix(idx, nph, er);
+    }
+
+// --------------------------------------------------------------------------
+//
+// 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
+//
+Bool_t MCerPhotEvt::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    MCerPhotPix *pix = GetPixById(idx);
+
+    if (!pix || !pix->IsPixelUsed())
+        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;
+    default:
+        val = pix->GetNumPhotons()*ratio;
+        return kTRUE;
+    }
+    return kTRUE;
+}
+
+void MCerPhotEvt::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MCerPhotEvt::DrawPixelContent - not available." << endl;
+}
+
+TObject *MCerPhotEvtIter::Next()
+{
+    if (!fUsedOnly)
+        return TObjArrayIter::Next();
+
+    MCerPhotPix *pix;
+    while ((pix = (MCerPhotPix*)TObjArrayIter::Next()))
+        if (pix->IsPixelUsed())
+            return pix;
+    return pix;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotEvt.h	(revision 3781)
@@ -0,0 +1,89 @@
+#ifndef MARS_MCerPhotEvt
+#define MARS_MCerPhotEvt
+
+#ifndef ROOT_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+#ifndef MARS_MCerPhotPix
+#include "MCerPhotPix.h"
+#endif
+
+class MGeomCam;
+class MCerPhotPix;
+class MCerPhotEvtIter;
+
+class MCerPhotEvt : public MParContainer, public MCamEvent
+{
+    friend class MCerPhotEvtIter;
+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?
+
+public:
+    MCerPhotEvt(const char *name=NULL, const char *title=NULL);
+    ~MCerPhotEvt() { delete fPixels; }
+
+    UInt_t GetNumPixels() const { return fNumPixels; }
+    //void   InitSize(UInt_t num) { fPixels->Expand(num); }
+
+    MCerPhotPix *AddPixel(Int_t idx, Float_t nph=0, Float_t er=0);
+
+    void FixSize();
+
+    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;
+
+    MCerPhotPix &operator[](int i)       { return *(MCerPhotPix*)(fPixels->UncheckedAt(i)); }
+    MCerPhotPix &operator[](int i) const { return *(MCerPhotPix*)(fPixels->UncheckedAt(i)); }
+
+    void Scale(Double_t f) { fPixels->ForEach(MCerPhotPix, Scale)(f); }
+    void RemoveUnusedPixels();
+
+    MCerPhotPix *GetPixById(Int_t idx) const;
+
+    void Reset();
+
+    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;
+
+    operator TIterator*() const;
+
+    ClassDef(MCerPhotEvt, 2)    // class for an event containing cerenkov photons
+};
+
+class MCerPhotEvtIter : public TObjArrayIter
+{
+private:
+    Bool_t fUsedOnly;
+public:
+    MCerPhotEvtIter(const MCerPhotEvt *evt, Bool_t usedonly=kTRUE, Bool_t dir=kIterForward) : TObjArrayIter(evt->fPixels, dir), fUsedOnly(usedonly) { }
+    TObject *Next();
+    TIterator &operator=(const TIterator &) { return *this; }
+    ClassDef(MCerPhotEvtIter, 0)
+};
+
+inline MCerPhotEvt::operator TIterator*() const { return new MCerPhotEvtIter(this); }
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.cc	(revision 3781)
@@ -0,0 +1,79 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MCerPhotPix
+//
+// 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
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MCerPhotPix.h"
+
+#include "MLog.h"
+
+ClassImp(MCerPhotPix);
+
+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.
+//
+MCerPhotPix::MCerPhotPix(Int_t pix, Float_t phot, Float_t errphot) :
+    fPixId(pix), fRing(1), fIsCore(kFALSE), fPhot(phot), fErrPhot(errphot), 
+    fIsSaturated(kFALSE), fIsHGSaturated(kFALSE)
+{
+} 
+
+// --------------------------------------------------------------------------
+//
+//  Print information to gLog.
+//
+void MCerPhotPix::Print(Option_t *) const
+{ 
+    gLog << GetDescriptor() <<" Pixel: "<< fPixId;
+    gLog << (fRing>0?"   Used ":" Unused ");
+    gLog << (fIsCore?" Core ":"      ");
+    gLog << (fIsSaturated?"   ":"not") << " saturated ";
+    gLog << "High gain " << (fIsHGSaturated?"   ":"not") << " saturated ";
+    gLog << "Nphot= " << fPhot << " Error(Nphot)=" << fErrPhot << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCerPhotPix.h	(revision 3781)
@@ -0,0 +1,66 @@
+#ifndef MARS_MCerPhotPix_H
+#define MARS_MCerPhotPix_H
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MCerPhotPix : public MParContainer
+{
+private:
+
+    Int_t    fPixId;     // the pixel Id
+
+   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)
+    Bool_t   fIsCore;    // the pixel is a Core pixel -> kTRUE
+
+    Float_t  fPhot;      // The number of Cerenkov photons
+    Float_t  fErrPhot;   // the error of fPhot
+
+    Bool_t   fIsSaturated;   // the pixel's low gain is saturated
+    Bool_t   fIsHGSaturated; // the pixel's high gain is saturated
+
+    // FIXME: arrival time t, and it's error sigma t
+
+public:
+    MCerPhotPix(Int_t pix=-1, Float_t phot=0, Float_t errphot=0);
+
+    Int_t    GetPixId() const            { return fPixId;   }
+    Float_t  GetNumPhotons() const       { return fPhot;    }
+    Float_t  GetErrorPhot() const        { return fErrPhot; }
+    
+    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     SetRing(UShort_t r)         { fRing = r;   }
+    Short_t  GetRing() const             { return fRing;}
+
+    void     SetPixelCore()              { fIsCore = kTRUE; }
+    Bool_t   IsPixelCore() const         { return fIsCore;  }
+
+    void     SetNumPhotons(Float_t f)    { fPhot    = f; }
+    void     SetErrorPhot(Float_t f)     { fErrPhot = f; }
+    void     Set(Float_t np, Float_t ep) { fPhot = np; fErrPhot = ep; }
+
+    void     SetPixelSaturated()         { fIsSaturated = kTRUE; }
+    Bool_t   IsPixelSaturated() const    { return fIsSaturated; }
+
+    void     SetPixelHGSaturated()         { fIsHGSaturated = kTRUE; }
+    Bool_t   IsPixelHGSaturated() const    { return fIsHGSaturated; }
+
+    void     AddNumPhotons(Float_t f)    { fPhot += f; }
+
+    void     Scale(Float_t f)            { fPhot/=f; }
+
+    void     Print(Option_t *opt = NULL) const;
+
+    ClassDef(MCerPhotPix, 4)  // class containing information about the Cerenkov Photons in a pixel
+};
+
+#endif
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MCompProbCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEst.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEst.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEst.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEst.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEst.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEst.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParam.h	(revision 3781)
@@ -0,0 +1,67 @@
+#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);
+
+    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-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstParamDanielMkn421.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.cc	(revision 3781)
@@ -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  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                                             //
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MEnergyEstimate.h"
+
+#include "MParList.h"
+
+#include "MMcEvt.hxx"
+#include "MHillas.h"
+#include "MEnergyEst.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MEnergyEstimate);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEnergyEstimate::MEnergyEstimate(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MEnergyEstimate";
+    fTitle = title ? title : "Task to estimate the energy";
+
+    AddToBranchList("MMcEvt.fEnergy");
+}
+
+Int_t MEnergyEstimate::PreProcess(MParList *plist)
+{
+   fHillas = (MHillas*)plist->FindObject("MHillas");
+   if (!fHillas)
+   {
+       *fLog << err << dbginf << "MHillas not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << err << dbginf << "MMcEvt not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   fEnergy = (MEnergyEst*)plist->FindCreateObj("MEnergyEst");
+   if (!fEnergy)
+      return kFALSE;
+
+   return kTRUE;    
+}
+
+Int_t MEnergyEstimate::Process()
+{
+  //fEnergy->SetEnergy(fHillas->GetSize());
+  fEnergy->SetEnergy(fMcEvt->GetEnergy());
+  return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEnergyEstimate.h	(revision 3781)
@@ -0,0 +1,29 @@
+#ifndef MARS_MEnergyEstimate
+#define MARS_MEnergyEstimate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MMcEvt;
+class MHillas;
+class MEnergyEst;
+
+class MEnergyEstimate : public MTask
+{
+private:
+    MMcEvt     *fMcEvt;
+    MHillas    *fHillas;
+    MEnergyEst *fEnergy;
+
+public:
+    MEnergyEstimate(const char *name=NULL, const char *title=NULL);
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    ClassDef(MEnergyEstimate, 0) // Task to copy the MC energy (preliminary)
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEventRate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.cc	(revision 3781)
@@ -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, 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)
+//
+//
+//  Input Containers:
+//    MTime
+//
+//  Output Containers:
+//    MEventRate
+//    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 "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MEventRate.h"
+
+ClassImp(MEventRateCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MEventRateCalc::MEventRateCalc(const char *name, const char *title)
+    : fTimes(1000)
+{
+    fName  = name  ? name  : "MEventRateCalc";
+    fTitle = title ? title : "Calculate trigger rate";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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("MTime");
+    if (!fTime)
+    {
+        *fLog << err << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRate = (MEventRate*)pList->FindCreateObj("MEventRate");
+    if (!fRate)
+        return kFALSE;
+
+    fTimes.Reset();
+
+    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;
+
+    const UInt_t n = fTimes.GetSize();
+
+    const UInt_t n1 = exec;
+    const UInt_t n2 = exec>=n ? exec+1 : 0;
+
+    fTimes[n1%n] = *fTime;
+
+    const UInt_t cnt = n1<n2 ? n : n1-n2;
+
+    const Double_t rate = (Double_t)cnt/(fTimes[n1%n]-fTimes[n2%n]);
+
+    fRate->SetRate(exec>1?rate:0, cnt);
+    fRate->SetReadyToSave();
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MEventRateCalc.h	(revision 3781)
@@ -0,0 +1,42 @@
+#ifndef MARS_MEventRateCalc
+#define MARS_MEventRateCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+#ifndef MARS_MTime
+#include "MTime.h"
+#endif
+#ifndef ROOT_TArrayD
+#include <TArrayD.h>
+#endif
+
+class MEventRate;
+
+class MEventRateCalc : public MTask
+{
+    MTime      *fTime;  //!
+    MEventRate *fRate;  //!
+
+    //ULong_t fEvtNumber; //!
+    //MTime   fEvtTime;   //!
+
+    //UInt_t  fNumEvents;
+
+    TArrayD fTimes;     //!
+
+
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MEventRateCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNumEvents(ULong_t num) { /*fNumEvents = num;*/ fTimes.Set(num); }
+
+    ClassDef(MEventRateCalc, 0)// Task to calculate event rates
+};
+ 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFiltercutsCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MFindSupercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MGeomApply.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MGeomApply.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MGeomApply.cc	(revision 3781)
@@ -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): Thomas Bretz, 09/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!              Markus Gaug,  03/2004 <mailto:markus@ifae.es>
+!
+!   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
+//   MBlindPixels
+//   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.
+// 
+//  Input Containers:
+//   [MGeomCam]
+//
+//  Output Containers:
+//   [MPedestalCam]
+//   [MCalibrationChargeCam]
+//   [MCalibrationRelTimeCam]
+//   [MCalibrationQECam]
+//   [MCalibrationPedCam]
+//   [MPedPhotCam]
+//   [MExtractedSignalCam]
+//   [MBlindPixels]
+//   [MArrivalTime]
+//   [MArrivalTimeCam]
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MGeomApply.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.h"
+#include "MPedestalCam.h"
+#include "MCalibrationCam.h"
+#include "MPedPhotCam.h"
+#include "MExtractedSignalCam.h"
+#include "MBlindPixels.h"
+#include "MArrivalTimeCam.h"
+#include "MArrivalTime.h"
+#include "MBadPixelsCam.h"
+
+ClassImp(MGeomApply);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. MGeomCamMagic is the default geometry.
+//
+MGeomApply::MGeomApply(const char *name, const char *title) : fGeomName("MGeomCamMagic")
+{
+    fName  = name  ? name  : "MGeomApply";
+    fTitle = title ? title : "Task to apply geometry settings";
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Try to find 'MGeomCam' in the Parameter List. If it is not found,
+//  processing is stopped.
+//
+//  The size of MPedestalCam and MBlindPixels is set accordingly.
+//
+Bool_t MGeomApply::ReInit(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!cam)
+    {
+       *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.
+    cam->CalcPixRatio();
+
+    MPedestalCam *ped = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (ped)
+        ped->Init(*cam);
+
+    MCalibrationCam *cal = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationChargeCam"));
+    if (cal)
+        cal->Init(*cam);
+
+    MCalibrationCam *cat = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationRelTimeCam"));
+    if (cat)
+        cat->Init(*cam);
+
+    MCalibrationCam *qe = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationQECam"));
+    if (qe)
+        qe->Init(*cam);
+
+    MCalibrationCam *pcam = (MCalibrationCam*)pList->FindObject(AddSerialNumber("MCalibrationPedCam"));
+    if (pcam)
+        pcam->Init(*cam);
+
+    MPedPhotCam *pedphot = (MPedPhotCam*)pList->FindObject(AddSerialNumber("MPedPhotCam"));
+    if (pedphot)
+        pedphot->InitSize(cam->GetNumPixels());
+
+    MExtractedSignalCam *ext = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+    if (ext)
+        ext->InitSize(cam->GetNumPixels());
+
+    MBlindPixels *bnd = (MBlindPixels*)pList->FindObject(AddSerialNumber("MBlindPixels"));
+    if (bnd)
+        bnd->InitSize(cam->GetNumPixels());
+
+    MArrivalTimeCam *tme = (MArrivalTimeCam*)pList->FindObject(AddSerialNumber("MArrivalTimeCam"));
+    if (tme)
+      tme->InitSize(cam->GetNumPixels());
+
+    MArrivalTime    *atm = (MArrivalTime*)pList->FindObject(AddSerialNumber("MArrivalTime"));
+    if (atm)
+      atm->InitSize(cam->GetNumPixels());
+
+    MBadPixelsCam *bad = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (bad)
+      bad->InitSize(cam->GetNumPixels());
+
+    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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MGeomApply.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MGeomApply.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MGeomApply.h	(revision 3781)
@@ -0,0 +1,28 @@
+#ifndef MARS_MGeomApply
+#define MARS_MGeomApply
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MParList;
+
+class MGeomApply : public MTask
+{
+private:
+    TString fGeomName; // Name of geometry class
+
+    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);
+
+    void SetGeometry(TString geom) { fGeomName = geom; }
+
+    ClassDef(MGeomApply, 0) // Task to apply geometry settings
+};
+    
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.cc	(revision 3781)
@@ -0,0 +1,572 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 MHGausEvents-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
+// +- MHGausEvents::fPickupLimit (default: 5) sigma (see MHGausEvents::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are
+// taken directly (see MHGausEvents::BypassFit()).
+//
+// Outliers of more than MHGausEvents::fPickupLimit (default: 5) sigmas
+// from the mean are counted as Pickup events (stored in MHGausEvents::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"
+
+ClassImp(MHPedestalCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Initializes:
+// - fExtractHiGainSlices to 0.
+// - fExtractLoGainSlices to 0.
+//
+MHPedestalCam::MHPedestalCam(const char *name, const char *title) 
+    : fExtractHiGainSlices(0.), fExtractLoGainSlices(0.)
+{
+    fName  = name  ? name  : "MHPedestalCam";
+    fTitle = title ? title : "";
+
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// 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
+// 
+// Sets number of bins to MHCalibrationCam::fAverageNbins for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+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 ");
+
+        InitPedHists((MHPedestalPix&)GetAverageHiGainArea(j),j,fExtractHiGainSlices);
+
+        GetAverageHiGainArea(j).GetHGausHist()->SetTitle("Pedestals average Area Idx ");
+        GetAverageHiGainArea(j).SetNbins(fAverageNbins);
+      }
+  }
+
+  if (fAverageLoGainAreas->GetEntries()==0)
+  {
+    fAverageLoGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageLoGainAreas)[j] = 
+          new MHPedestalPix("AverageLoGainArea",
+                                      "Pedestals average Area idx ");
+
+        InitPedHists((MHPedestalPix&)GetAverageLoGainArea(j),j,fExtractLoGainSlices);
+
+        GetAverageLoGainArea(j).GetHGausHist()->SetTitle("Pedestals average Area Idx ");
+        GetAverageLoGainArea(j).SetNbins(fAverageNbins);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetEntries()==0)
+  {
+      fAverageHiGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageHiGainSectors)[j] = 
+            new MHPedestalPix("AverageHiGainSector",
+                                        "Pedestals average sector ");
+
+          InitPedHists((MHPedestalPix&)GetAverageHiGainSector(j),j,fExtractHiGainSlices);
+
+          GetAverageHiGainSector(j).GetHGausHist()->SetTitle("Pedestals average Sector ");
+          GetAverageHiGainSector(j).SetNbins(fAverageNbins);
+      }
+  }
+
+  if (fAverageLoGainSectors->GetEntries()==0)
+  {
+      fAverageLoGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageLoGainSectors)[j] = 
+            new MHPedestalPix("AverageLoGainSector",
+                                        "Pedestals average sector ");
+
+          InitPedHists((MHPedestalPix&)GetAverageLoGainSector(j),j,fExtractLoGainSlices);
+          
+          GetAverageLoGainSector(j).GetHGausHist()->SetTitle("Pedestals average Sector ");
+          GetAverageLoGainSector(j).SetNbins(fAverageNbins);
+      }
+  }
+
+  return kTRUE;
+}
+
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsBad():
+// - calls MHGausEvents::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHGausEvents::ChangeHistId(i)
+// - MHGausEvents::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);
+  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++)
+  {
+      MHGausEvents &histhi = (*this)[i];
+      MHGausEvents &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++)
+    {
+      MHGausEvents &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+      MHGausEvents &histlo = GetAverageLoGainArea(j);
+      histlo.FillHistAndArray(numarealo[j] == 0 ? 0. : sumarealo[j]/numarealo[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHGausEvents &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+      MHGausEvents &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-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalCam.h	(revision 3781)
@@ -0,0 +1,38 @@
+#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
+
+  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;
+  
+  ClassDef(MHPedestalCam, 1)	// Histogram class for Charge Camera Pedestals 
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.cc	(revision 3781)
@@ -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): 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 MHGausEvents, 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
+//
+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  );
+
+  // 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-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHPedestalPix.h	(revision 3781)
@@ -0,0 +1,36 @@
+#ifndef MARS_MHPedestalPix
+#define MARS_MHPedestalPix
+
+#ifndef MARS_MHGausEvents
+#include "MHGausEvents.h"
+#endif
+
+class MHPedestalPix : public MHGausEvents
+{
+
+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-8-4/MagicSoft/Mars/manalysis/MHadronness.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHadronness.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHadronness.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MHadronness.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHadronness.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MHadronness.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMarquardt.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMarquardt.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMarquardt.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMarquardt.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMarquardt.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMarquardt.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.cc	(revision 3781)
@@ -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  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  = "MMatrixLoop";
+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();
+}
+
+// --------------------------------------------------------------------------
+//
+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-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMatrixLoop.h	(revision 3781)
@@ -0,0 +1,30 @@
+#ifndef MARS_MMatrixLoop
+#define MARS_MMatrixLoop
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+
+class MHMatrix;
+
+class MMatrixLoop : public MTask
+{
+private:
+    static const TString gsDefName;
+    static const TString gsDefTitle;
+
+protected:
+    MHMatrix *fMatrix;
+    Int_t     fNumRow;    //! Number of dimensions of histogram
+
+public:
+    MMatrixLoop(MHMatrix *mat, const char *name=NULL, const char *title=NULL);
+
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+
+    ClassDef(MMatrixLoop, 0) // Task 'reading' events from a MHMatrix
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.cc	(revision 3781)
@@ -0,0 +1,347 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 photons and ADC counts 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.
+//
+//  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"
+
+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";
+
+    //
+    // As default we set 1 photon = 1 ADC count.
+    // (this will make Size to be in ADC counts if no previous calibration has been made)
+    // Hence:
+    //
+    fADC2PhElInner = MCalibrationQEPix::gkDefaultAverageQE;
+    fADC2PhElOuter = MCalibrationQEPix::gkDefaultAverageQE;
+
+    fAmplitude = -1.;
+    fAmplitudeOuter = -1.;
+    fConversionHiLo = -1.;
+
+    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 = 1;  // 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 MCalibrationCam already existed in the parameter list before
+    // MMcCalibrationUpdate::PreProcess was executed (from a 
+    // previous calibration loop) we must not fill it, hence nothing
+    // else has to be done in ReInit:
+    //
+    if (!fFillCalibrationCam)
+        return kTRUE;
+
+    //
+    // Set the ADC to photons conversion factor for outer pixels.
+    // One can choose not to apply the known (in MC) gain factor between
+    // inner and outer pixels, (fOuterPixelsGainScaling = kFALSE),
+    // which may be useful for display purposes.
+    //
+
+    if (fOuterPixelsGainScaling)
+      fADC2PhElOuter = fADC2PhElInner * (fAmplitude / fAmplitudeOuter);
+    else
+      fADC2PhElOuter = fADC2PhElInner;
+
+
+    const int num = fCalCam->GetSize();
+
+    fCalCam->SetFFactorMethodValid   ( kTRUE );
+    fQECam->SetFFactorMethodValid    ( kTRUE );
+    fQECam->SetBlindPixelMethodValid ( kTRUE );
+    fQECam->SetCombinedMethodValid   ( kTRUE );
+    fQECam->SetPINDiodeMethodValid   ( kTRUE );  
+    
+    for (int 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.);
+
+    }
+
+
+    return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCerPhotPed object
+//
+Int_t MMcCalibrationUpdate::Process()
+{
+    const int num = fCalCam->GetSize();
+
+    for (int 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];
+
+	qepix.SetAvNormFFactor(1.);
+	// This factor should convert the default average QE to average QE for a spectrum
+	// like that of Cherenkov light. See the documentration of MCalibrationQEPix.
+
+        Float_t qe       = qepix.GetAverageQE();
+	Float_t adc2phot = calpix.GetMeanConvFADC2Phe() / qe;
+	Float_t hi2lo    = calpix.GetConversionHiLo();
+
+	if (sigpix.IsLoGainUsed())
+            pedpix.Set(adc2phot*hi2lo*pedestmean, adc2phot*hi2lo*pedestrms);
+	else
+            pedpix.Set(adc2phot*pedestmean, adc2phot*pedestrms);
+
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcCalibrationUpdate.h	(revision 3781)
@@ -0,0 +1,55 @@
+#ifndef MARS_MMcCalibrationUpdate
+#define MARS_MMcCalibrationUpdate
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MPedPhotCam;
+class MGeomCam;
+class MMcFadcHeader;
+class MExtractedSignalCam;
+
+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.
+
+public:
+    MMcCalibrationUpdate(const char *name=NULL, const char *title=NULL);
+
+    void SetOuterPixelsGainScaling(Bool_t tf) 
+      { fOuterPixelsGainScaling = tf; }
+
+    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-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalCopy.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcPedestalNSBAdd.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.cc	(revision 3781)
@@ -0,0 +1,1008 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2.h	(revision 3781)
@@ -0,0 +1,97 @@
+#ifndef MARS_MMcTriggerLvl2
+#define MARS_MMcTriggerLvl2
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcTrig;
+class MMcEvt;
+class MGeomCamMagic;
+class MGeomCam;
+class MGeomPix;
+
+class MMcTriggerLvl2 : public MParContainer
+{
+ 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);    
+
+  ClassDef(MMcTriggerLvl2,0) // Container for 2nd Level Trigger selection parameters 
+    };  
+    
+#endif      
+    
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.cc	(revision 3781)
@@ -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): 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 "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";
+  
+} 
+
+
+// --------------------------------------------------------------------------
+//                                                                         
+//  PreProcess
+//
+//
+Int_t MMcTriggerLvl2Calc::PreProcess (MParList *pList)
+{
+    // connect the raw data with this task
+
+    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;
+      }
+    fMMcTriggerLvl2 = (MMcTriggerLvl2*)pList->FindObject("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-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMcTriggerLvl2Calc.h	(revision 3781)
@@ -0,0 +1,45 @@
+#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();
+
+ public:
+    MMcTriggerLvl2Calc(const char *name=NULL, const char *title=NULL);   
+
+    ClassDef(MMcTriggerLvl2Calc, 0) // Task to calculate the MMcTriggerLvl2 Parameters
+};
+
+#endif 
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMinuitInterface.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.cc	(revision 3781)
@@ -0,0 +1,226 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "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-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MMultiDimDistCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPad.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPad.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPad.cc	(revision 3781)
@@ -0,0 +1,2370 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 "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(MPad);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MPad::MPad(const char *name, const char *title) 
+{
+  fName  = name  ? name  : "MPad";
+  fTitle = title ? title : "Task for the padding";
+
+  fType = "";
+
+  fHSigmaThetaMC     = NULL;
+  fHSigmaThetaON     = NULL;
+  fHSigmaThetaOFF    = NULL;
+
+  fHDiffPixThetaMC   = NULL;
+  fHDiffPixThetaON   = NULL;
+  fHDiffPixThetaOFF  = NULL;
+
+  fHSigmaPixThetaMC   = NULL;
+  fHSigmaPixThetaON   = NULL;
+  fHSigmaPixThetaOFF  = NULL;
+
+  fHgMC  = NULL;
+  fHgON  = NULL;
+  fHgOFF = NULL;
+
+  fHBlindPixIdThetaMC  = NULL;
+  fHBlindPixIdThetaON  = NULL;
+  fHBlindPixIdThetaOFF = NULL;
+
+  fHBlindPixNThetaMC   = NULL;
+  fHBlindPixNThetaON   = NULL;
+  fHBlindPixNThetaOFF  = NULL;
+
+  fHSigmaPedestal = NULL;
+  fHPhotons       = NULL;
+  fHNSB           = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MPad::~MPad()
+{
+  delete fHgMC;
+  delete fHgON;
+  delete fHgOFF;
+
+  delete fHSigmaTheta;
+  delete fHSigmaPixTheta;
+  delete fHDiffPixTheta;
+  delete fHBlindPixNTheta;
+  delete fHBlindPixIdTheta;
+
+  delete fHSigmaPedestal;
+  delete fHPhotons;
+  delete fHNSB;
+
+  delete fInfile;
+}
+// --------------------------------------------------------------------------
+//
+// 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 )
+{
+  // 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
+
+  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;
+
+  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 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 
+  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);
+
+    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 &c = *(MH::MakeDefCanvas("Merging", "", 600, 600)); 
+  c.Divide(2, 2);
+  gROOT->SetSelectedPad(NULL);
+
+  c.cd(1);
+  hista->SetDirectory(NULL);
+  hista->DrawCopy();
+  hista->SetBit(kCanDelete);    
+
+  c.cd(2);
+  histb->SetDirectory(NULL);
+  histb->DrawCopy();
+  histb->SetBit(kCanDelete);    
+
+  c.cd(3);
+  histap->SetDirectory(NULL);
+  histap->DrawCopy();
+  histap->SetBit(kCanDelete);    
+
+  //--------------------------------------------------------------------
+
+  delete histc;
+  delete histbp;
+  delete histcp;
+
+  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(
+   TH2D *sigthmc,  TH3D *diffpixthmc,  TH3D *sigmapixthmc,
+   TH2D *blindidthmc,  TH2D *blindnthmc,
+   TH2D *sigthon,  TH3D *diffpixthon,  TH3D *sigmapixthon,
+   TH2D *blindidthon,  TH2D *blindnthon,
+   TH2D *sigthoff, TH3D *diffpixthoff, TH3D *sigmapixthoff,
+   TH2D *blindidthoff, TH2D *blindnthoff)
+{
+  *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( (TH2D&)*sigthon );
+  fHSigmaTheta->SetNameTitle("2D-ThetaSigmabar", "2D-ThetaSigmabar (target)");
+
+  fHDiffPixTheta = new TH3D( (TH3D&)*diffpixthon );
+  fHDiffPixTheta->SetNameTitle("3D-ThetaPixDiff", "3D-ThetaPixDiff (target)");
+
+  fHSigmaPixTheta = new TH3D( (TH3D&)*sigmapixthon );
+  fHSigmaPixTheta->SetNameTitle("3D-ThetaPixSigma", "3D-ThetaPixSigma (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)");
+
+  //--------------------------
+  fHSigmaThetaMC = sigthmc;
+  fHSigmaThetaMC->SetNameTitle("2D-ThetaSigmabarMC", "2D-ThetaSigmabarMC (orig.)");
+  fHSigmaThetaON = sigthon;
+  fHSigmaThetaON->SetNameTitle("2D-ThetaSigmabarON", "2D-ThetaSigmabarON (orig.)");
+  fHSigmaThetaOFF = sigthoff;
+  fHSigmaThetaOFF->SetNameTitle("2D-ThetaSigmabarOFF", "2D-ThetaSigmabarOFF (orig.)");
+
+  //--------------------------
+  fHBlindPixNThetaMC = blindnthmc;
+  fHBlindPixNThetaMC->SetNameTitle("2D-ThetaBlindNMC", "2D-ThetaBlindNMC (orig.)");
+  fHBlindPixNThetaON = blindnthon;
+  fHBlindPixNThetaON->SetNameTitle("2D-ThetaBlindNON", "2D-ThetaBlindNON (orig.)");
+  fHBlindPixNThetaOFF = blindnthoff;
+  fHBlindPixNThetaOFF->SetNameTitle("2D-ThetaBlindNOFF", "2D-ThetaBlindNOFF (orig.)");
+
+  //--------------------------
+  fHBlindPixIdThetaMC = blindidthmc;
+  fHBlindPixIdThetaMC->SetNameTitle("2D-ThetaBlindIdMC", "2D-ThetaBlindIdMC (orig.)");
+  fHBlindPixIdThetaON = blindidthon;
+  fHBlindPixIdThetaON->SetNameTitle("2D-ThetaBlindIdON", "2D-ThetaBlindIdON (orig.)");
+  fHBlindPixIdThetaOFF = blindidthoff;
+  fHBlindPixIdThetaOFF->SetNameTitle("2D-ThetaBlindIdOFF", "2D-ThetaBlindIdOFF (orig.)");
+
+  //--------------------------
+  fHDiffPixThetaMC = diffpixthmc;
+  fHDiffPixThetaMC->SetNameTitle("3D-ThetaPixDiffMC", "3D-ThetaPixDiffMC (orig.)");
+  fHDiffPixThetaON = diffpixthon;
+  fHDiffPixThetaON->SetNameTitle("3D-ThetaPixDiffON", "3D-ThetaPixDiffON (orig.)");
+  fHDiffPixThetaOFF = diffpixthoff;
+  fHDiffPixThetaOFF->SetNameTitle("3D-ThetaPixDiffOFF", "3D-ThetaPixDiffOFF (orig.)");
+
+  //--------------------------
+  fHSigmaPixThetaMC = sigmapixthmc;
+  fHSigmaPixThetaMC->SetNameTitle("3D-ThetaPixSigmaMC", "3D-ThetaPixSigmaMC (orig.)");
+  fHSigmaPixThetaON = sigmapixthon;
+  fHSigmaPixThetaON->SetNameTitle("3D-ThetaPixSigmaON", "3D-ThetaPixSigmaON (orig.)");
+  fHSigmaPixThetaOFF = sigmapixthoff;
+  fHSigmaPixThetaOFF->SetNameTitle("3D-ThetaPixSigmaOFF", "3D-ThetaPixSigmaOFF (orig.)");
+  //--------------------------
+
+
+  // get binning for fHgON, fHgOFF and fHgMC  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 << all << "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 << 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");
+
+  //............   loop over Theta bins   ...........................
+
+
+
+  *fLog << all << "MPad::MergeONOFFMC(); bins of Theta, Sigmabarold, Sigmabarnew, fraction of events to be padded" << endl;
+  for (Int_t l=1; l<=nbinstheta; l++)
+  {
+    TH2D * fHga = new TH2D;
+    MH::SetBinning(fHga, &binsg, &binsg);
+    TH2D * fHgb = new TH2D;
+    MH::SetBinning(fHgb, &binsg, &binsg);
+
+    //-------------------------------------------
+    // merge ON and OFF distributions
+    // input : hista is the normalized 1D distr. of sigmabar for ON  data
+    //         histb is the normalized 1D distr. of sigmabar for OFF data
+    // output : histap    will be the merged distribution (ON-OFF)
+    //          fHga(k,j) will tell which fraction of ON events should be 
+    //                    padded from bin k to bin j
+    //          fHgb(k,j) will tell which fraction of OFF events should be 
+    //                    padded from bin k to bin j
+
+    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);
+
+    Merge2Distributions(hista, histb, histap, fHga, fHgb, nbinssig);
+    delete hista;
+    delete histb;
+
+    // fill fHgON and fHgOFF
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = fHga->GetBinContent(k,j);
+        fHga->SetBinContent (k, j, 0.0);
+        fHgON->SetBinContent(l, k, j, a);
+
+        Double_t b = fHgb->GetBinContent(k,j);
+        fHgb->SetBinContent (k, j, 0.0);
+        fHgOFF->SetBinContent(l, k, j, b);
+      }
+
+    //-------------------------------------------
+    // now merge ON-OFF and MC distributions
+    // input : hista is the result of the merging of ON and OFF distributions  
+    //         histb is the normalized 1D distr. of sigmabar for MC data
+    // output : histap    will be the merged distribution (target distribution)
+    //          fHga(k,j) will tell which fraction of ON, OFF events should be 
+    //                    padded from bin k to bin j
+    //          fHgb(k,j) will tell which fraction of MC events should be 
+    //                    padded from bin k to bin j
+
+    hista  = new TH1D( (const TH1D&)*histap);
+
+    histb  = sigthmc->ProjectionY("sigmc_y", l, l, "");
+    sumb = histb->Integral();
+    histb->Scale(1./sumb);
+
+    Merge2Distributions(hista, histb, histap, fHga, fHgb, nbinssig);
+    delete hista;
+    delete histb;
+
+    // update fHgON and fHgOFF and fill fHgMC
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a   =  fHga->GetBinContent  (k,j);
+
+        Double_t aON = fHgON->GetBinContent(l,k,j);
+        fHgON->SetBinContent(l, k, j, aON+a);
+
+        Double_t aOFF = fHgOFF->GetBinContent(l,k,j);
+        fHgOFF->SetBinContent(l, k, j, aOFF+a);
+
+        Double_t b = fHgb->GetBinContent(k,j);
+        fHgMC->SetBinContent(l, k, j, b);
+      }
+
+    // fill target distribution fHSigmaTheta 
+    // (only for plotting, it will not  be used in the padding)
+    for (Int_t j=1; j<=nbinssig; j++)
+    {
+      Double_t a = histap->GetBinContent(j);
+      fHSigmaTheta->SetBinContent(l, j, a);
+    }
+
+    delete fHga;
+    delete fHgb;
+
+    delete histap;
+  }
+  //............   end of loop over Theta bins   ....................
+
+  
+  // Define the target distributions 
+  //        fHDiffPixTheta, fHSigmaPixTheta
+  //               (they are calculated as 
+  //               averages of the ON and OFF distributions)
+  //        fHBlindPixNTheta, fHBlindPixIdTheta
+  //               (they are calculated as 
+  //               the sum of the ON and OFF distributions)
+  // (fHDiffPixTheta will be used in the padding of MC events)
+
+  //............   start of new loop over Theta bins   ....................
+  for (Int_t j=1; j<=nbinstheta; j++)
+  {
+    // fraction of ON/OFF/MC events to be padded : fracON, fracOFF, fracMC
+
+    Double_t fracON  = fHgON->Integral (j, j, 1, nbinssig, 1, nbinssig, "");
+    Double_t fracOFF = fHgOFF->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+    Double_t fracMC  = fHgMC->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+
+    Double_t normON;
+    Double_t normOFF;
+
+    // set ranges for 2D-projections of 3D-histograms
+    TAxis *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 << all << "Theta bin j : fracON, fracOFF, facON, facOFF = " 
+          << j << ",  " << fracON << ",  " << fracOFF << ",  "
+          << fracMC << ",  " << facON << ",  " << facOFF << endl; 
+
+    //------------------------------------------------------------------
+    // define target distribution  'sigma^2-sigmavar^2 vs. pixel number'
+    ay = diffpixthon->GetYaxis();
+    Int_t nbinspixel = ay->GetNbins();
+
+    TAxis *az = diffpixthon->GetZaxis();
+    Int_t nbinsdiff = az->GetNbins();
+
+    hist    = (TH2D*)diffpixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histOFF = (TH2D*)diffpixthoff->Project3D("zy");
+
+    normON  = hist->Integral();
+    normOFF = histOFF->Integral();
+    if (normON  != 0.0) hist->Scale(1.0/normON);
+    if (normOFF != 0.0) histOFF->Scale(1.0/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;
+
+    //------------------------------------------------------------------
+    // define target distribution  'sigma vs. pixel number'
+    ay = sigmapixthon->GetYaxis();
+    nbinspixel = ay->GetNbins();
+
+    az = sigmapixthon->GetZaxis();
+    Int_t nbinssigma = az->GetNbins();
+
+    hist    = (TH2D*)sigmapixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histOFF = (TH2D*)sigmapixthoff->Project3D("zy");
+
+    normON  = hist->Integral();
+    normOFF = histOFF->Integral();
+    if (normON  != 0.0) hist->Scale(1.0/normON);
+    if (normOFF != 0.0) histOFF->Scale(1.0/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<=nbinssigma; l++)
+      {
+        Double_t cont = hist->GetBinContent(k,l);
+        fHSigmaPixTheta->SetBinContent(j, k, l, cont);  
+      }
+
+    delete hist;
+    delete histOFF;
+
+
+    //------------------------------------------------------------------
+    // define target distribution  'number of blind pixels per event'
+    ay = blindnthon->GetYaxis();
+    Int_t nbinsn = ay->GetNbins();
+
+    hist1    = fHBlindPixNThetaON->ProjectionY("", j, j, "");
+    hist1->SetName("dummy");
+    hist1OFF = fHBlindPixNThetaOFF->ProjectionY("", j, j, "");
+
+    normON  = hist1->Integral();
+    normOFF = hist1OFF->Integral();
+    if (normON  != 0.0) hist1->Scale(1.0/normON);
+    if (normOFF != 0.0) hist1OFF->Scale(1.0/normOFF);
+
+    // sum of ON and OFF distributions
+    hist1->Add(hist1OFF, 1.0); 
+    hist1->Scale( 1.0/hist1->Integral() );
+
+    for (Int_t k=1; k<=nbinsn; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixNTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1OFF;
+
+    //------------------------------------------------------------------
+    // define target distribution  'id of blind pixel'
+    ay = blindidthon->GetYaxis();
+    Int_t nbinsid = ay->GetNbins();
+
+    hist1    = fHBlindPixIdThetaON->ProjectionY("", j, j, "");
+    hist1->SetName("dummy");
+    hist1OFF = fHBlindPixIdThetaOFF->ProjectionY("", j, j, "");
+
+    // divide by the number of events (from fHBlindPixNTheta)
+    if (normON  != 0.0) hist1->Scale(1.0/normON);
+    if (normOFF != 0.0) hist1OFF->Scale(1.0/normOFF);
+
+    // sum of ON and OFF distributions
+    hist1->Add(hist1OFF, 1.0); 
+
+    for (Int_t k=1; k<=nbinsid; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixIdTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1OFF;
+  }
+  //............   end of new loop over Theta bins   ....................
+
+  *fLog << all 
+        << "MPad::MergeONOFFMC(); The target distributions for the padding have been created" 
+        << endl;
+  *fLog << all << "----------------------------------------------------------" 
+        << endl;
+  //--------------------------------------------
+
+  fHSigmaThetaMC->SetDirectory(NULL);
+  fHSigmaThetaON->SetDirectory(NULL);
+  fHSigmaThetaOFF->SetDirectory(NULL);
+
+  fHDiffPixThetaMC->SetDirectory(NULL);
+  fHDiffPixThetaON->SetDirectory(NULL);
+  fHDiffPixThetaOFF->SetDirectory(NULL);
+
+  fHSigmaPixThetaMC->SetDirectory(NULL);
+  fHSigmaPixThetaON->SetDirectory(NULL);
+  fHSigmaPixThetaOFF->SetDirectory(NULL);
+
+  fHBlindPixIdThetaMC->SetDirectory(NULL);
+  fHBlindPixIdThetaON->SetDirectory(NULL);
+  fHBlindPixIdThetaOFF->SetDirectory(NULL);
+
+  fHBlindPixNThetaMC->SetDirectory(NULL);
+  fHBlindPixNThetaON->SetDirectory(NULL);
+  fHBlindPixNThetaOFF->SetDirectory(NULL);
+
+  fHgMC->SetDirectory(NULL);
+  fHgON->SetDirectory(NULL);
+  fHgOFF->SetDirectory(NULL);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Merge the distributions 
+//   fHSigmaTheta      2D-histogram  (Theta, sigmabar)
+//
+// ===>   of ON and MC data   <==============
+//
+// and define the matrices fHgMC and fHgON  
+//
+// These matrices tell which fraction of events should be padded 
+// from bin k of sigmabar to bin j
+//
+
+Bool_t MPad::MergeONMC(
+   TH2D *sigthmc,  TH3D *diffpixthmc,  TH3D *sigmapixthmc,
+   TH2D *blindidthmc,  TH2D *blindnthmc,
+   TH2D *sigthon,  TH3D *diffpixthon,  TH3D *sigmapixthon,
+   TH2D *blindidthon,  TH2D *blindnthon)
+{
+  *fLog << all << "----------------------------------------------------------------------------------" << endl;
+  *fLog << all << "MPad::MergeONMC(); Merge the ON  and MC histograms to obtain the target distributions for the padding"
+        << endl;
+
+  fHSigmaTheta = new TH2D( (TH2D&)*sigthon );
+  fHSigmaTheta->SetNameTitle("2D-ThetaSigmabar", "2D-ThetaSigmabar (target)");
+
+  fHDiffPixTheta = new TH3D( (TH3D&)*diffpixthon );
+  fHDiffPixTheta->SetNameTitle("3D-ThetaPixDiff", "3D-ThetaPixDiff (target)");
+
+  fHSigmaPixTheta = new TH3D( (TH3D&)*sigmapixthon );
+  fHSigmaPixTheta->SetNameTitle("3D-ThetaPixSigma", "3D-ThetaPixSigma (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)");
+
+  //--------------------------
+  fHSigmaThetaMC = sigthmc;
+  fHSigmaThetaMC->SetNameTitle("2D-ThetaSigmabarMC", "2D-ThetaSigmabarMC (orig.)");
+  fHSigmaThetaON = sigthon;
+  fHSigmaThetaON->SetNameTitle("2D-ThetaSigmabarON", "2D-ThetaSigmabarON (orig.)");
+
+  //--------------------------
+  fHBlindPixNThetaMC = blindnthmc;
+  fHBlindPixNThetaMC->SetNameTitle("2D-ThetaBlindNMC", "2D-ThetaBlindNMC (orig.)");
+  fHBlindPixNThetaON = blindnthon;
+  fHBlindPixNThetaON->SetNameTitle("2D-ThetaBlindNON", "2D-ThetaBlindNON (orig.)");
+
+  //--------------------------
+  fHBlindPixIdThetaMC = blindidthmc;
+  fHBlindPixIdThetaMC->SetNameTitle("2D-ThetaBlindIdMC", "2D-ThetaBlindIdMC (orig.)");
+  fHBlindPixIdThetaON = blindidthon;
+  fHBlindPixIdThetaON->SetNameTitle("2D-ThetaBlindIdON", "2D-ThetaBlindIdON (orig.)");
+
+  //--------------------------
+  fHDiffPixThetaMC = diffpixthmc;
+  fHDiffPixThetaMC->SetNameTitle("3D-ThetaPixDiffMC", "3D-ThetaPixDiffMC (orig.)");
+  fHDiffPixThetaON = diffpixthon;
+  fHDiffPixThetaON->SetNameTitle("3D-ThetaPixDiffON", "3D-ThetaPixDiffON (orig.)");
+
+  //--------------------------
+  fHSigmaPixThetaMC = sigmapixthmc;
+  fHSigmaPixThetaMC->SetNameTitle("3D-ThetaPixSigmaMC", "3D-ThetaPixSigmaMC (orig.)");
+  fHSigmaPixThetaON = sigmapixthon;
+  fHSigmaPixThetaON->SetNameTitle("3D-ThetaPixSigmaON", "3D-ThetaPixSigmaON (orig.)");
+
+  //--------------------------
+
+
+  // get binning for fHgON and fHgMC  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 << all << "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 << 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");
+
+
+  //............   loop over Theta bins   ...........................
+
+
+
+  *fLog << all << "MPad::MergeONMC(); bins of Theta, Sigmabarold, Sigmabarnew, fraction of events to be padded" << endl;
+  for (Int_t l=1; l<=nbinstheta; l++)
+  {
+    TH2D * fHga = new TH2D;
+    MH::SetBinning(fHga, &binsg, &binsg);
+    TH2D * fHgb = new TH2D;
+    MH::SetBinning(fHgb, &binsg, &binsg);
+
+    //-------------------------------------------
+    // merge ON and MC distributions
+    // input : hista is the normalized 1D distr. of sigmabar for ON data
+    //         histb is the normalized 1D distr. of sigmabar for MC data
+    // output : histap    will be the merged distribution (ON-MC)
+    //          fHga(k,j) will tell which fraction of ON events should be 
+    //                    padded from bin k to bin j
+    //          fHgb(k,j) will tell which fraction of MC events should be 
+    //                    padded from bin k to bin j
+
+    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  = sigthmc->ProjectionY("sigmc_y", l, l, "");
+    Stat_t sumb = histb->Integral();
+    histb->Scale(1./sumb);
+
+    Merge2Distributions(hista, histb, histap, fHga, fHgb, nbinssig);
+    delete hista;
+    delete histb;
+
+    // fill fHgON and fHgMC
+    for (Int_t k=1; k<=nbinssig; k++)
+      for (Int_t j=1; j<=nbinssig; j++)
+      {
+        Double_t a = fHga->GetBinContent(k,j);
+        fHga->SetBinContent (k, j, 0.0);
+        fHgON->SetBinContent(l, k, j, a);
+
+        Double_t b = fHgb->GetBinContent(k,j);
+        fHgb->SetBinContent (k, j, 0.0);
+        fHgMC->SetBinContent(l, k, j, b);
+      }
+
+
+    // fill target distribution fHSigmaTheta 
+    // (only for plotting, it will not  be used in the padding)
+    for (Int_t j=1; j<=nbinssig; j++)
+    {
+      Double_t a = histap->GetBinContent(j);
+      fHSigmaTheta->SetBinContent(l, j, a);
+    }
+
+    delete fHga;
+    delete fHgb;
+
+    delete histap;
+  }
+  //............   end of loop over Theta bins   ....................
+
+  
+  // Define the target distributions 
+  //        fHDiffPixTheta, fHSigmaPixTheta
+  //               (they are calculated as 
+  //               averages of the ON and MCdistributions)
+  //        fHBlindPixNTheta, fHBlindPixIdTheta
+  //               (they are calculated as 
+  //               the sum of the ON and MC distributions)
+  // (fHDiffPixTheta will be used in the padding of MC events)
+
+  //............   start of new loop over Theta bins   ....................
+  for (Int_t j=1; j<=nbinstheta; j++)
+  {
+    // fraction of ON/MC events to be padded : fracON, fracMC
+
+    Double_t fracON  = fHgON->Integral (j, j, 1, nbinssig, 1, nbinssig, "");
+    Double_t fracMC  = fHgMC->Integral(j, j, 1, nbinssig, 1, nbinssig, "");
+
+    Double_t normON;
+    Double_t normMC;
+
+    // set ranges for 2D-projections of 3D-histograms
+    TAxis *ax = diffpixthon->GetXaxis();
+    ax->SetRange(j, j);
+    ax = diffpixthmc->GetXaxis();
+    ax->SetRange(j, j);
+
+    TH2D *hist;
+    TH2D *histMC;
+
+    TH1D *hist1;
+    TH1D *hist1MC;
+
+    // weights for ON and MC distrubtions when
+    // calculating the weighted average
+    Double_t facON = 0.5 * (1. - fracON + fracMC);
+    Double_t facMC = 0.5 * (1. + fracON - fracMC);
+  
+    *fLog << all << "Theta bin j : fracON, fracMC, facON, facMC = " 
+          << j << ",  " << fracON << ",  " << fracMC << ",  "
+          << facON << ",  " << facMC << endl; 
+
+    //------------------------------------------------------------------
+    // define target distribution  'sigma^2-sigmavar^2 vs. pixel number'
+    ay = diffpixthon->GetYaxis();
+    Int_t nbinspixel = ay->GetNbins();
+
+    TAxis *az = diffpixthon->GetZaxis();
+    Int_t nbinsdiff = az->GetNbins();
+
+    hist    = (TH2D*)diffpixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histMC = (TH2D*)diffpixthmc->Project3D("zy");
+
+    normON  = hist->Integral();
+    normMC = histMC->Integral();
+    if (normON  != 0.0) hist->Scale(1.0/normON);
+    if (normMC != 0.0)  histMC->Scale(1.0/normMC);
+
+    // weighted average of ON and MC distributions
+    hist->Scale(facON);
+    hist->Add(histMC, facMC); 
+
+    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 histMC;
+
+    //------------------------------------------------------------------
+    // define target distribution  'sigma vs. pixel number'
+    ay = sigmapixthon->GetYaxis();
+    nbinspixel = ay->GetNbins();
+
+    az = sigmapixthon->GetZaxis();
+    Int_t nbinssigma = az->GetNbins();
+
+    hist    = (TH2D*)sigmapixthon->Project3D("zy");
+    hist->SetName("dummy");
+    histMC = (TH2D*)sigmapixthmc->Project3D("zy");
+
+    normON  = hist->Integral();
+    normMC = histMC->Integral();
+    if (normON  != 0.0) hist->Scale(1.0/normON);
+    if (normMC != 0.0) histMC->Scale(1.0/normMC);
+
+    // weighted average of ON and MC distributions
+    hist->Scale(facON);
+    hist->Add(histMC, facMC); 
+
+    for (Int_t k=1; k<=nbinspixel; 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 histMC;
+
+
+    //------------------------------------------------------------------
+    // define target distribution  'number of blind pixels per event'
+    ay = blindnthon->GetYaxis();
+    Int_t nbinsn = ay->GetNbins();
+
+    hist1    = fHBlindPixNThetaON->ProjectionY("", j, j, "");
+    hist1->SetName("dummy");
+    hist1MC  = fHBlindPixNThetaMC->ProjectionY("", j, j, "");
+
+    normON  = hist1->Integral();
+    normMC  = hist1MC->Integral();
+    if (normON  != 0.0) hist1->Scale(1.0/normON);
+    if (normMC != 0.0)  hist1MC->Scale(1.0/normMC);
+
+    // sum of ON and MC distributions
+    hist1->Add(hist1MC, 1.0); 
+    hist1->Scale( 1.0/hist1->Integral() );
+
+    for (Int_t k=1; k<=nbinsn; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixNTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1MC;
+
+    //------------------------------------------------------------------
+    // define target distribution  'id of blind pixel'
+    ay = blindidthon->GetYaxis();
+    Int_t nbinsid = ay->GetNbins();
+
+    hist1    = fHBlindPixIdThetaON->ProjectionY("", j, j, "");
+    hist1->SetName("dummy");
+    hist1MC = fHBlindPixIdThetaMC->ProjectionY("", j, j, "");
+
+    // divide by the number of events (from fHBlindPixNTheta)
+    if (normON  != 0.0) hist1->Scale(1.0/normON);
+    if (normMC != 0.0)  hist1MC->Scale(1.0/normMC);
+
+    // sum of ON and MC distributions
+    hist1->Add(hist1MC, 1.0); 
+
+    for (Int_t k=1; k<=nbinsid; k++)
+      {
+        Double_t cont = hist1->GetBinContent(k);
+        fHBlindPixIdTheta->SetBinContent(j, k, cont);  
+      }
+
+    delete hist1;
+    delete hist1MC;
+  }
+  //............   end of new loop over Theta bins   ....................
+
+  *fLog << all 
+        << "MPad::MergeONMC(); The target distributions for the padding have been created" 
+        << endl;
+  *fLog << all << "----------------------------------------------------------" 
+        << endl;
+  //--------------------------------------------
+
+  fHSigmaThetaMC->SetDirectory(NULL);
+  fHSigmaThetaON->SetDirectory(NULL);
+
+  fHDiffPixThetaMC->SetDirectory(NULL);
+  fHDiffPixThetaON->SetDirectory(NULL);
+
+  fHSigmaPixThetaMC->SetDirectory(NULL);
+  fHSigmaPixThetaON->SetDirectory(NULL);
+
+  fHBlindPixIdThetaMC->SetDirectory(NULL);
+  fHBlindPixIdThetaON->SetDirectory(NULL);
+
+  fHBlindPixNThetaMC->SetDirectory(NULL);
+  fHBlindPixNThetaON->SetDirectory(NULL);
+
+  fHgMC->SetDirectory(NULL);
+  fHgON->SetDirectory(NULL);
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Read padding distributions from a file
+//
+//
+Bool_t MPad::ReadPaddingDist(const char* namefilein)
+{
+  *fLog << all << "MPad : Read padding histograms from file " 
+        << namefilein << endl;
+
+  fInfile = new TFile(namefilein);
+  fInfile->ls();
+
+    //------------------------------------
+      fHSigmaThetaMC = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabarMC");
+      if (!fHSigmaThetaMC)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaSigmabarMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaSigmabarMC' was read in" << endl;
+
+      fHSigmaThetaON = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabarON");
+      if (!fHSigmaThetaON)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaSigmabarON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaSigmabarON' was read in" << endl;
+
+      fHSigmaThetaOFF = 
+      (TH2D*) gROOT->FindObject("2D-ThetaSigmabarOFF");
+      if (!fHSigmaThetaOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaSigmabarOFF' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad:Object '2D-ThetaSigmabarOFF' was read in" << endl;
+
+    //------------------------------------
+      fHDiffPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiff");
+      if (!fHDiffPixTheta)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixDiff' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixDiff' was read in" << endl;
+
+      fHDiffPixThetaMC = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiffMC");
+      if (!fHDiffPixThetaMC)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixDiffMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixDiffMC' was read in" << endl;
+
+      fHDiffPixThetaON = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiffON");
+      if (!fHDiffPixThetaON)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixDiffON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixDiffON' was read in" << endl;
+
+      fHDiffPixThetaOFF = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixDiffOFF");
+      if (!fHDiffPixThetaOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixDiffOFF' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixDiffOFF' was read in" << endl;
+
+
+    //------------------------------------
+       fHSigmaPixTheta = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigma");
+      if (!fHSigmaPixTheta)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixSigma' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixSigma' was read in" << endl;
+
+       fHSigmaPixThetaMC = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigmaMC");
+      if (!fHSigmaPixThetaMC)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixSigmaMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixSigmaMC' was read in" << endl;
+
+      fHSigmaPixThetaON = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigmaON");
+      if (!fHSigmaPixThetaON)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixSigmaON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixSigmaON' was read in" << endl;
+
+      fHSigmaPixThetaOFF = 
+      (TH3D*) gROOT->FindObject("3D-ThetaPixSigmaOFF");
+      if (!fHSigmaPixThetaOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-ThetaPixSigmaOFF' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-ThetaPixSigmaOFF' was read in" << endl;
+
+    //------------------------------------
+      fHgMC = 
+      (TH3D*) gROOT->FindObject("3D-PaddingMatrixMC");
+      if (!fHgMC)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-PaddingMatrixMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-PaddingMatrixMC' was read in" << endl;
+
+      fHgON = 
+      (TH3D*) gROOT->FindObject("3D-PaddingMatrixON");
+      if (!fHgON)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-PaddingMatrixON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-PaddingMatrixON' was read in" << endl;
+
+      fHgOFF = 
+      (TH3D*) gROOT->FindObject("3D-PaddingMatrixOFF");
+      if (!fHgOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '3D-PaddingMatrixOFF' not found on root file"
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '3D-PaddingMatrixOFF' was read in" << endl;
+
+    //------------------------------------
+      fHBlindPixIdThetaMC = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindIdMC");
+      if (!fHBlindPixIdThetaMC)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindIdMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindIdMC' was read in" << endl;
+
+      fHBlindPixIdThetaON = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindIdON");
+      if (!fHBlindPixIdThetaON)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindIdON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindIdON' was read in" << endl;
+
+      fHBlindPixIdThetaOFF = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindIdOFF");
+      if (!fHBlindPixIdThetaOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindIdOFF' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindIdMC' was read in" << endl;
+
+    //------------------------------------
+      fHBlindPixNThetaMC = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindNMC");
+      if (!fHBlindPixNThetaMC)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindNMC' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindNMC' was read in" << endl;
+
+      fHBlindPixNThetaON = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindNON");
+      if (!fHBlindPixNThetaON)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindNON' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindNON' was read in" << endl;
+
+      fHBlindPixNThetaOFF = 
+      (TH2D*) gROOT->FindObject("2D-ThetaBlindNOFF");
+      if (!fHBlindPixNThetaOFF)
+	{
+          *fLog << all 
+                << "MPad : Object '2D-ThetaBlindNOFF' not found on root file" 
+                << endl;
+          return kFALSE;
+	}
+      *fLog << all 
+            << "MPad : Object '2D-ThetaBlindNOFF' was read in" << endl;
+
+    //------------------------------------
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Write padding distributions onto a file
+//
+//
+Bool_t MPad::WritePaddingDist(const char* namefileout)
+{
+  *fLog << all << "MPad : Write padding histograms onto file " 
+        << namefileout << endl;
+
+  TFile outfile(namefileout, "RECREATE");
+
+  fHBlindPixNThetaMC->Write();
+  fHBlindPixNThetaON->Write();
+  fHBlindPixNThetaOFF->Write();
+
+  fHBlindPixIdThetaMC->Write();
+  fHBlindPixIdThetaON->Write();
+  fHBlindPixIdThetaOFF->Write();
+
+  fHSigmaThetaMC->Write();
+  fHSigmaThetaON->Write();
+  fHSigmaThetaOFF->Write();
+
+  fHDiffPixTheta->Write();
+  fHDiffPixThetaMC->Write();
+  fHDiffPixThetaON->Write();
+  fHDiffPixThetaOFF->Write();
+
+  fHSigmaPixTheta->Write();
+  fHSigmaPixThetaMC->Write();
+  fHSigmaPixThetaON->Write();
+  fHSigmaPixThetaOFF->Write();
+
+  fHgMC->Write();
+  fHgON->Write();
+  fHgOFF->Write();
+
+  *fLog << all 
+        << "MPad::WriteTargetDist(); padding 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 MPad::SetDataType(const char* type)
+{
+  fType = type;
+  *fLog << all << "MPad::SetDataType(); type of data to be padded : " 
+        << fType << endl; 
+
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Set the pointers and prepare the histograms
+//
+Int_t MPad::PreProcess(MParList *pList)
+{
+  if ( !fHSigmaThetaMC     || !fHSigmaThetaON     || !fHSigmaThetaOFF      ||  
+       !fHDiffPixThetaMC   || !fHDiffPixThetaON   || !fHDiffPixThetaOFF    ||
+       !fHBlindPixIdThetaMC|| !fHBlindPixIdThetaON|| !fHBlindPixIdThetaOFF ||
+       !fHBlindPixNThetaMC || !fHBlindPixNThetaON || !fHBlindPixNThetaOFF  ||
+       !fHgMC              || !fHgON              || !fHgOFF                 )
+  { 
+       *fLog << err 
+             << "MPad : 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 << "MPad : MMcEvt not found... aborting." 
+             << endl;
+       return kFALSE;
+     }
+  
+   fPed = (MPedPhotCam*)pList->FindObject("MPedPhotCam");
+   if (!fPed)
+     {
+       *fLog << err << "MPad : MPedPhotCam not found... aborting." 
+             << endl;
+       return kFALSE;
+     }
+
+   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;
+     }
+
+   fSigmabar = (MSigmabar*)pList->FindCreateObj("MSigmabar");
+   if (!fSigmabar)
+     {
+       *fLog << err << "MPad : MSigmabar not found... aborting." << endl;
+       return kFALSE;
+     }
+
+   fBlinds = (MBlindPixels*)pList->FindCreateObj("MBlindPixels");
+   if (!fBlinds)
+     {
+       *fLog << err << "MPad : MBlindPixels not found... aborting." 
+             << endl;
+       return kFALSE;
+     }
+   
+   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, 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));
+   memset(fWarnings, 0, sizeof(fWarnings));
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Do the Padding (noise adjustment)
+//
+// input for the padding : 
+//  - the matrices fHgON, fHgOFF, fHgMC
+//  - the original distributions fHBlindPixNTheta, fHBlindPixIdTheta
+//                               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.95 * 0.90 * 0.13 * 0.9;
+
+  //------------------------------------------------
+  // 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();
+
+  //-------------------------------------------
+  // Calculate average sigma of the event
+  //
+  Double_t sigbarold_phot = fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  *fLog << all << "MPad::Process(); before padding : " << endl;
+  fSigmabar->Print("");
+  Double_t sigbarold  = sigbarold_phot * fPEperPhoton;
+  Double_t sigbarold2 = sigbarold*sigbarold;
+
+  const Double_t theta = kRad2Deg*fMcEvt->GetTelescopeTheta();
+  *fLog << all << "theta = " << theta << endl;
+
+  Int_t binTheta = fHBlindPixNTheta->GetXaxis()->FindBin(theta);
+  if ( binTheta < 1  ||  binTheta > fHBlindPixNTheta->GetNbinsX() )
+  {
+    *fLog << warn 
+          << "MPad::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_phot bin
+
+  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, "");
+  nTheta = hn->Integral();
+  Int_t binSigma = hn->FindBin(sigbarold_phot);
+  nSigma = hn->GetBinContent(binSigma);
+
+   *fLog << all           
+         << "Theta, sigbarold_phot, binTheta, binSigma, nTheta, nSigma = "
+         << theta << ",  " << sigbarold_phot << ",  " << binTheta << ",  "
+         << binSigma << ",  " << nTheta << ",  " << nSigma   << endl;      
+
+  delete hn;
+  
+
+  //-------------------------------------------
+  // for the current theta :
+  //     generate blind pixels according to the histograms 
+  //     fHBlindPixNTheta and fHBlindPixIDTheta
+  //
+  // ON  : add the blind pixels from the OFF data
+  // OFF : add the blind pixels from the ON data
+  // MC  : add the blind pixels from the ON and OFF data
+
+  //-----------------------------------
+  if (fType == "ON"  ||  fType == "MC")
+  {
+    // numBlind is the number of blind pixels in an event
+    TH1D *nblind;
+    UInt_t numBlind;
+
+    nblind = fHBlindPixNThetaOFF->ProjectionY("", binTheta, binTheta, "");
+    if ( nblind->Integral() == 0.0 )
+    {
+      *fLog << warn << "MPad::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;
+
+
+    // throw the Id of numBlind different pixels in this event
+    if ( numBlind > 0)
+    {
+      TH1D *hblind;
+      UInt_t idBlind;
+      UInt_t listId[npix];
+      UInt_t nlist = 0;
+      Bool_t equal;
+
+      hblind = fHBlindPixIdThetaOFF->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 << all << "idBlind = " << idBlind << endl;
+        }
+      fBlinds->SetReadyToSave();
+
+      delete hblind;
+    }
+  }
+
+  //------------------------------------
+  if (fType == "OFF"  ||  fType == "MC")
+  {
+    // throw numBlind;
+    // numBlind is the number of blind pixels in an event
+    TH1D *nblind;
+    UInt_t numBlind;
+
+    nblind = fHBlindPixNThetaON->ProjectionY("", binTheta, binTheta, "");
+    if ( nblind->Integral() == 0.0 )
+    {
+      *fLog << warn << "MPad::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;
+
+
+    // throw the Id of numBlind different pixels in this event
+    if ( numBlind > 0)
+    {
+      TH1D *hblind;
+      UInt_t idBlind;
+      UInt_t listId[npix];
+      UInt_t nlist = 0;
+      Bool_t equal;
+
+      hblind = fHBlindPixIdThetaON->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 << all << "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_phot);
+  *fLog << all << "binSig, sigbarold_phot = " << binSig << ",  " 
+          << sigbarold_phot << endl;
+
+  Double_t prob;
+  TH1D *hpad = NULL;
+
+  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;
+  }
+
+  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, fHgON = " << 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 = 8;
+    fErrors[rc]++;
+    return kTRUE;
+  }
+  // event should be padded
+  *fLog << all << "event will be padded" << endl;  
+
+
+  //-------------------------------------------
+  // for the current theta, generate a sigmabar :
+  //     for MC/ON/OFF data according to the matrix fHgMC/ON/OFF
+  //
+  Double_t sigmabar_phot = 0;
+  Double_t sigmabar      = 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;
+  //}
+
+  sigmabar_phot = hpad->GetRandom();
+  sigmabar = sigmabar_phot * fPEperPhoton;
+
+  *fLog << all << "sigmabar_phot = " << sigmabar_phot << endl;
+
+  delete hpad;
+  
+  const Double_t sigmabar2 = sigmabar*sigmabar;
+
+  //-------------------------------------------
+
+  *fLog << all << "MPad::Process(); sigbarold, sigmabar = " 
+        << sigbarold << ",  "<< sigmabar << endl;
+
+  // Skip event if target sigmabar is <= sigbarold
+  if (sigmabar <= sigbarold)
+  {
+    *fLog << all << "MPad::Process(); target sigmabar is less than sigbarold : "
+          << sigmabar << ",  " << sigbarold << ",   Skip event" << endl;
+
+    rc = 4;
+    fErrors[rc]++;
+    return kCONTINUE;     
+  }
+
+
+  //-------------------------------------------
+  //
+  // Calculate average number of NSB photo electrons 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;         // [photo electrons]  
+  Double_t F2excess  = 1.3;
+  Double_t lambdabar;        // [photo electrons]
+
+
+  Int_t bincheck = fHDiffPixTheta->GetXaxis()->FindBin(theta);
+  if (binTheta != bincheck)
+  {
+    *fLog << err 
+          << "MPad::Process(); 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 << err << "MPad::Process(); illegal data type... aborting" 
+          << endl;
+    return kERROR;
+  }
+
+  Double_t RMS_phot = hnoise->GetRMS(1);  
+  Double_t RMS = RMS_phot * fPEperPhoton * fPEperPhoton;
+  delete hnoise;
+
+  elNoise2 = TMath::Min(RMS,  sigmabar2 - sigbarold2);
+  *fLog << all << "elNoise2 = " << elNoise2 << endl; 
+
+  lambdabar = (sigmabar2 - sigbarold2 - elNoise2) / F2excess;  
+
+  // 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 sigma2      = 0;
+
+  Double_t diff_phot   = 0;
+  Double_t diff        = 0;
+
+  Double_t addSig2_phot= 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 << 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 ratioArea = 1.0 / fCam->GetPixRatio(j);
+
+    MPedPhotPix &ppix = (*fPed)[j];
+    Double_t oldsigma_phot = ppix.GetRms();
+    Double_t oldsigma = oldsigma_phot * fPEperPhoton;
+    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;
+
+    // throw the Sigma for this pixel from the distribution fHDiffPixTheta
+    // MC  : from fHDiffPixTheta
+    // ON  : from fHDiffPixThetaOFF
+    // OFF : from fHDiffPixThetaON
+
+    TH3D *sp = NULL;
+
+    if      (fType == "MC")  sp = fHDiffPixTheta;
+    else if (fType == "ON")  sp = fHDiffPixThetaOFF;
+    else if (fType == "OFF") sp = fHDiffPixThetaON;
+    else
+    {
+      *fLog << err << "MPad::Process(); illegal data type... aborting" 
+            << endl;
+      return kERROR;
+    }
+
+    hdiff = sp->ProjectionZ("", binTheta, binTheta,
+                                binPixel, binPixel, "");
+
+    if ( hdiff->GetEntries() == 0 )
+    {
+      *fLog << warn << "MPad::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_phot = hdiff->GetRandom();
+      diff = diff_phot * fPEperPhoton * fPEperPhoton;
+ 
+     // the following condition ensures that elNoise2Pix > 0.0 
+      if ( (diff + sigmabar2 - oldsigma2/ratioArea
+                               - lambdabar*F2excess) > 0.0 )
+      {
+        ok = kTRUE;
+        break;
+      }
+    }
+
+    if (!ok)
+    {
+      *fLog << all << "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;
+
+
+    //---------------------------------
+    // get the additional sigma^2 for this pixel (due to the padding)
+
+    addSig2 = sigma2*ratioArea - oldsigma2;
+    addSig2_phot = addSig2 / (fPEperPhoton * fPEperPhoton);
+
+    //---------------------------------
+    // get the additional electronic noise for this pixel
+
+    elNoise2Pix = addSig2 - lambdabar*F2excess*ratioArea;
+
+
+    //---------------------------------
+    // throw actual number of additional NSB photo electrons (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 << 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*ratioArea;
+    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/ratioArea );
+    fHPhotons->Fill( oldphotons_phot/ratioArea, 
+                     newphotons_phot/ratioArea );
+
+
+    // 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( oldsigma2 + addSig2 ); 
+    Double_t newsigma_phot = newsigma / fPEperPhoton; 
+    ppix.SetRms( newsigma_phot );
+
+    fHSigmaPedestal->Fill( oldsigma_phot, newsigma_phot );
+  } 
+  //----------   end of loop over pixels   ---------------------------------
+
+  // Calculate sigmabar again and crosscheck
+
+  fSigmabar->Calc(*fCam, *fPed, *fEvt);
+  *fLog << all << "MPad::Process(); after padding : " << endl;
+  fSigmabar->Print("");
+
+  *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(' ');
+
+    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("Pad", "", 900, 1500)); 
+    c.Divide(3, 5);
+    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 = NULL;
+    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 = NULL;
+    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 = NULL;
+    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 = NULL;
+    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(13);
+    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(14);
+    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);;
+
+    c.cd(15);
+    TH2D *m3;
+    m3 = (TH2D*) ((TH3*)fHgMC)->Project3D("zy");
+    m3->SetDirectory(NULL);
+    m3->SetTitle("(Target) Sigmabar-new vs. Sigmabar-old (MC, all  \\Theta)");
+    m3->SetXTitle("Sigmabar-old");
+    m3->SetYTitle("Sigmabar-new");
+
+    m3->DrawCopy("box");
+    m3->SetBit(kCanDelete);;
+
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPad.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPad.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPad.h	(revision 3781)
@@ -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 MMcEvt;
+class MSigmabar;
+class MParList;
+class MBlindPixels;
+class MRead;
+class MFilterList;
+
+
+class MPad : 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          fIter;
+
+    Int_t          fErrors[9];
+    Int_t          fWarnings[2];
+
+    //----------------------------------
+    // plots used for the padding
+    // for all plots it is assumed that the pedestal RMS is given in units of "number of photons"
+    TH2D  *fHBlindPixIdTheta;    // 2D-histogram (blind pixel Id vs. Theta)
+    TH2D  *fHBlindPixIdThetaMC;  // 2D-histogram (blind pixel Id vs. Theta)
+    TH2D  *fHBlindPixIdThetaON;  // 2D-histogram (blind pixel Id vs. Theta)
+    TH2D  *fHBlindPixIdThetaOFF; // 2D-histogram (blind pixel Id vs. Theta)
+
+    //---------------------
+    TH2D  *fHBlindPixNTheta;    // 2D-histogram (no.of blind pixels vs. Theta)
+    TH2D  *fHBlindPixNThetaMC;  // 2D-histogram (no.of blind pixels vs. Theta)
+    TH2D  *fHBlindPixNThetaON;  // 2D-histogram (no.of blind pixels vs. Theta)
+    TH2D  *fHBlindPixNThetaOFF; // 2D-histogram (no.of blind pixels vs. Theta)
+
+    //---------------------
+    TH2D  *fHSigmaTheta;       // 2D-histogram (sigmabar vs. Theta)
+    TH2D  *fHSigmaThetaMC;     // 2D-histogram (sigmabar vs. Theta)
+    TH2D  *fHSigmaThetaON;     // 2D-histogram (sigmabar vs. Theta)
+    TH2D  *fHSigmaThetaOFF;    // 2D-histogram (sigmabar vs. Theta)
+
+    //---------------------
+    TH3D  *fHDiffPixTheta;     // 3D-histogram (Theta, pixel, sigma^2-sigmabar^2)
+    TH3D  *fHDiffPixThetaMC;   // 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  *fHSigmaPixTheta;     // 3D-histogram (Theta, pixel, sigma)
+    TH3D  *fHSigmaPixThetaMC;   // 3D-histogram (Theta, pixel, sigma)
+    TH3D  *fHSigmaPixThetaON;   // 3D-histogram (Theta, pixel, sigma)
+    TH3D  *fHSigmaPixThetaOFF;  // 3D-histogram (Theta, pixel, sigma)
+
+    //---------------------
+    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
+
+    //-------------------------------
+    // 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
+
+
+    Bool_t Merge2Distributions(TH1D *hista, TH1D * histb, TH1D * histap,
+                               TH2D *fHga,  TH2D * fHgb, Int_t nbinssig);
+
+
+public:
+    MPad(const char *name=NULL, const char *title=NULL);
+    ~MPad();
+
+    Bool_t MergeONOFFMC(
+      TH2D *sigthmc,  TH3D *diffpixthmc, TH3D *sigmapixthmc,
+      TH2D *blindidthmc,  TH2D *blindnthmc,
+      TH2D *sigthon,  TH3D *diffpixthon, TH3D *sigmapixthon,
+      TH2D *blindidthon,  TH2D *blindnthon,
+      TH2D *sigthoff=NULL, TH3D *diffpixthoff=NULL,TH3D *sigmapixthoff=NULL,
+      TH2D *blindidthoff=NULL, TH2D *blindnthoff=NULL);
+
+    Bool_t MergeONMC(
+      TH2D *sigthmc,  TH3D *diffpixthmc, TH3D *sigmapixthmc,
+      TH2D *blindidthmc,  TH2D *blindnthmc,
+      TH2D *sigthon,  TH3D *diffpixthon, TH3D *sigmapixthon,
+      TH2D *blindidthon,  TH2D *blindnthon);
+
+    Bool_t ReadPaddingDist(const char *filein);
+    Bool_t WritePaddingDist(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();
+
+    ClassDef(MPad, 0)    // task for the padding 
+}; 
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPadding.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPadding.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPadding.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPadding.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPadding.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPadding.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MParameters.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MParameters.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MParameters.cc	(revision 3781)
@@ -0,0 +1,67 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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(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.
+//
+MParameterI::MParameterI(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MParameterI";
+    fTitle = title ? title : "Storgare container for general parameters (integer)";
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MParameters.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MParameters.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MParameters.h	(revision 3781)
@@ -0,0 +1,98 @@
+#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; }
+
+    ClassDef(MParameterD, 1) // Container to hold a generalized parameters (double)
+};
+
+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; }
+
+    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-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalUpdate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.cc	(revision 3781)
@@ -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): 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
+//
+//
+// Actually, MPedCalcPedRun applies the following formula (1):
+// 
+// PedRMS = Sqrt(  (sum(x_i^2) - sum(x_i)^2/n) / n-1 / 14 )
+// 
+// where x_i is the sum of 14 FADC slices and sum means the sum over all
+// events, n is the number of events.
+// 
+// For a high number of events, this formula is equivalent to formula (2):
+// 
+// PedRMS = Sqrt(  (<x_i*x_i> - <x_i>*<x_i>) / 14  )
+// 
+// where <> is the mean over all events and x_i again the sum over the 14
+// slices.
+// 
+// If you assume statistical equivalence of all slices (say, all have equal
+// offset and are not correlated and fluctuate Gaussian), it should also be
+// equivalent to (old formula) (3):
+// 
+// PedRMS = Sqrt(  (<p_i*p_i> - <p_i>*<p_i>) ) 
+// 
+// which is the RMS per slice of a single slice (p_i) and 
+// <> the mean over the total number of measurements, i.e. n*14.
+// 
+// If we assume that at least our pairs fluctuate independently and Gaussian,
+// then we can use the actual formula (1) in order to get 
+// fluctuations of pairs by the transformation:
+// 
+// PedRMS/pair = PedRMS (form. (3)) * Sqrt(2)
+// 
+// (However, we know that our slice-to-slice fluctuations are not Gaussian
+// (and moreover asymmetric) and that they are also correlated.)
+// 
+// 
+//  Input Containers:
+//   MRawEvtData
+//
+//  Output Containers:
+//   MPedestalCam
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedCalcPedRun.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 "MExtractedSignalPix.h"
+#include "MExtractedSignalCam.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MGeomCamMagic.h"
+
+ClassImp(MPedCalcPedRun);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// default constructor
+//
+MPedCalcPedRun::MPedCalcPedRun(const char *name, const char *title)
+    : fRawEvt(NULL), fPedestals(NULL)
+{
+    fName  = name  ? name  : "MPedCalcPedRun";
+    fTitle = title ? title : "Task to calculate pedestals from pedestal runs raw data";
+
+    AddToBranchList("fHiGainPixId");
+    AddToBranchList("fHiGainFadcSamples");
+
+    fNumHiGainSamples = 0;
+    Clear();
+}
+
+void MPedCalcPedRun::Clear(const Option_t *o)
+{
+
+  fNumSamplesTot    = 0;
+
+  fRawEvt    = NULL;
+  fPedestals = NULL;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Look for the following input containers:
+//
+//  - MRawEvtData
+// 
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedestalCam
+//
+Int_t MPedCalcPedRun::PreProcess( MParList *pList )
+{
+
+  Clear();
+  
+  fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+  if (!fRawEvt)
+    {
+      *fLog << err << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fGeom   =  (MGeomCam*)pList->FindObject("MGeomCam");
+  if (!fGeom)
+    {
+      *fLog << err << "MGeomCam not found... aborting." << endl;
+      return kFALSE;
+    }
+
+  fPedestals = (MPedestalCam*)pList->FindCreateObj("MPedestalCam");
+  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 MPedCalcPedRun::ReInit(MParList *pList)
+{
+    const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!runheader)
+    {
+        *fLog << warn << dbginf;
+        *fLog << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+    }
+    else
+      if (runheader->IsMonteCarloRun())
+        return kTRUE;
+
+    Int_t npixels  = fPedestals->GetSize();
+    Int_t areas    = fPedestals->GetAverageAreas();
+    Int_t sectors  = fPedestals->GetAverageSectors();
+
+    if (fSumx.GetSize()==0)
+    {
+	fSumx. Set(npixels);
+	fSumx2.Set(npixels);
+
+	fAreaSumx. Set(areas);
+	fAreaSumx2.Set(areas);
+	fAreaValid.Set(areas);
+
+	fSectorSumx. Set(sectors);
+	fSectorSumx2.Set(sectors);
+	fSectorValid.Set(sectors);
+
+	fSumx.Reset();
+	fSumx2.Reset();
+    }
+
+    // Calculate an even number for the hi gain samples to avoid
+    // biases due to the fluctuation in pedestal from one slice to
+    // the other one
+    fNumHiGainSamples = runheader->GetNumSamplesHiGain() & ~1;
+
+    return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// 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::Process()
+{
+
+  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();      
+
+      Byte_t *ptr = pixel.GetHiGainSamples();
+      const Byte_t *end = ptr + fNumHiGainSamples;
+      
+      UInt_t sum = 0;
+      UInt_t sqr = 0;
+
+      do
+        {
+          sum += *ptr;
+          sqr += *ptr * *ptr;
+        }
+      while (++ptr != end);
+      
+      const Float_t msum = (Float_t)sum;
+      
+      //
+      // These three lines have been uncommented by Markus Gaug
+      // If anybody needs them, please contact me!!
+      //
+      //	const Float_t higainped = msum/fNumHiGainSamples;
+      //	const Float_t higainrms = TMath::Sqrt((msqr-msum*msum/fNumHiGainSamples)/(fNumHiGainSamples-1.));
+      //	(*fPedestals)[idx].Set(higainped, higainrms);
+      
+      fSumx[idx]          += msum;
+      fAreaSumx[aidx]     += msum;
+      fSectorSumx[sector] += msum;      
+      //
+      // The old version:
+      //
+      //       const Float_t msqr = (Float_t)sqr;
+      //	fSumx2[idx] += msqr;
+      //
+      // The new version:
+      //
+      const Float_t sqrsum  = msum*msum;
+      fSumx2[idx]          += sqrsum;
+      fAreaSumx2[aidx]     += sqrsum;
+      fSectorSumx2[sector] += sqrsum;      
+    }
+  
+  fPedestals->SetReadyToSave();
+  fNumSamplesTot += fNumHiGainSamples;
+  
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Compute signal mean and rms in the whole run and store it in MPedestalCam
+//
+Int_t MPedCalcPedRun::PostProcess()
+{
+
+  // Compute pedestals and rms from the whole run
+  const ULong_t n     = fNumSamplesTot;
+  const ULong_t nevts = GetNumExecutions();
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  
+  while (pixel.Next())
+    {
+
+      const Int_t  pixid  = pixel.GetPixelId();
+      const UInt_t aidx   = (*fGeom)[pixid].GetAidx();
+      const UInt_t sector = (*fGeom)[pixid].GetSector();      
+      
+      fAreaValid  [aidx]++;
+      fSectorValid[sector]++;
+
+      const Float_t sum  = fSumx.At(pixid);
+      const Float_t sum2 = fSumx2.At(pixid);
+      
+      const Float_t higainped = sum/n;
+      //
+      // The old version:
+      //
+      //      const Float_t higainrms = TMath::Sqrt((sum2-sum*sum/n)/(n-1.));
+      //
+      // The new version:
+      //
+      // 1. Calculate the Variance of the sums:
+      Float_t higainVar = (sum2-sum*sum/nevts)/(nevts-1.);
+      // 2. Scale the variance to the number of slices:
+      higainVar /= (Float_t)fNumHiGainSamples;
+      // 3. Calculate the RMS from the Variance:
+      const Float_t higainrms = TMath::Sqrt(higainVar);
+
+      (*fPedestals)[pixid].Set(higainped, higainrms);
+
+    }
+
+  //
+  // Loop over the (two) area indices to get the averaged pedestal per aidx
+  //
+  for (Int_t aidx=0; aidx<fAreaValid.GetSize(); aidx++)
+    {
+      
+      const Int_t   napix = fAreaValid.At(aidx);
+      const Float_t sum   = fAreaSumx.At(aidx);
+      const Float_t sum2  = fAreaSumx2.At(aidx);
+      const ULong_t an    = napix * n;
+      const ULong_t aevts = napix * nevts;
+      
+      const Float_t higainped = sum/an;
+
+      // 1. Calculate the Variance of the sums:
+      Float_t higainVar = (sum2-sum*sum/aevts)/(aevts-1.);
+      // 2. Scale the variance to the number of slices:
+      higainVar /= (Float_t)fNumHiGainSamples;
+      // 3. Calculate the RMS from the Variance:
+      Float_t higainrms = TMath::Sqrt(higainVar);
+      // 4. Re-scale it with the square root of the number of involved pixels 
+      //    in order to be comparable to the mean of pedRMS of that area
+      higainrms *= TMath::Sqrt((Float_t)napix);
+
+      fPedestals->GetAverageArea(aidx).Set(higainped, higainrms);
+    }
+  
+  //
+  // Loop over the (six) sector indices to get the averaged pedestal per sector
+  //
+  for (Int_t sector=0; sector<fSectorValid.GetSize(); sector++)
+    {
+      
+      const Int_t   nspix = fSectorValid.At(sector);
+      const Float_t sum   = fSectorSumx.At(sector);
+      const Float_t sum2  = fSectorSumx2.At(sector);
+      const ULong_t sn    = nspix * n;
+      const ULong_t sevts = nspix * nevts;
+      
+      const Float_t higainped = sum/sn;
+
+      // 1. Calculate the Variance of the sums:
+      Float_t higainVar = (sum2-sum*sum/sevts)/(sevts-1.);
+      // 2. Scale the variance to the number of slices:
+      higainVar /= (Float_t)fNumHiGainSamples;
+      // 3. Calculate the RMS from the Variance:
+      Float_t higainrms = TMath::Sqrt(higainVar);
+      // 4. Re-scale it with the square root of the number of involved pixels 
+      //    in order to be comparable to the mean of pedRMS of that sector
+      higainrms *= TMath::Sqrt((Float_t)nspix);
+
+      fPedestals->GetAverageSector(sector).Set(higainped, higainrms);
+    }
+  
+  fPedestals->SetTotalEntries(fNumSamplesTot);
+
+  return kTRUE;
+}
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedCalcPedRun.h	(revision 3781)
@@ -0,0 +1,53 @@
+#ifndef MARS_MPedCalcPedRun
+#define MARS_MPedCalcPedRun
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+class MRawEvtData;
+class MPedestalCam;
+class MGeomCam;
+class MPedCalcPedRun : public MTask
+{
+
+  Byte_t fNumHiGainSamples;
+  UInt_t fNumSamplesTot;
+  
+  MRawEvtData  *fRawEvt;     // raw event data (time slices)
+  MPedestalCam *fPedestals;  // Pedestals of all pixels in the camera
+  MGeomCam     *fGeom;       // Camera geometry
+  
+  TArrayF fSumx;         // sum of values
+  TArrayF fSumx2;        // sum of squared values
+  TArrayF fAreaSumx;     // averaged sum of values per area idx
+  TArrayF fAreaSumx2;    // averaged sum of squared values per area idx
+  TArrayI fAreaValid;    // number of valid pixel with area idx  
+  TArrayF fSectorSumx;   // averaged sum of values per sector 
+  TArrayF fSectorSumx2;  // averaged sum of squared values per sector
+  TArrayI fSectorValid;  // number of valid pixel with sector idx  
+  
+  Int_t  PreProcess ( MParList *pList );
+  Bool_t ReInit     ( MParList *pList );
+  Int_t  Process    ();
+  Int_t  PostProcess();
+  
+public:
+
+  MPedCalcPedRun(const char *name=NULL, const char *title=NULL);
+  
+  void Clear(const Option_t *o="");
+  void SetNumHiGainSamples(const Byte_t n)      { fNumHiGainSamples = n;   }
+  
+  ClassDef(MPedCalcPedRun, 0)   // Task to calculate pedestals from pedestal runs raw data
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.cc	(revision 3781)
@@ -0,0 +1,202 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   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:
+//   MCerPhotEvt
+//
+//  Output Containers:
+//   MPedPhotCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCalc.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MRawRunHeader.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.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:
+//
+//  - MCerPhotEvt
+//  - 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 = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+  if (!fCerPhot)
+    {
+      *fLog << err << "MPedPhotCalc::PreProcess Error: MCerPhotEvt not found... aborting." << endl;
+      return kFALSE;
+    }
+
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+    {
+      *fLog << warn << "MPedPhotCalc::PreProcess Warning: No MBadPixelsCam found." << 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)
+{
+  const MRawRunHeader *runheader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+  if (!runheader)
+  {
+      *fLog << warn << dbginf;
+      *fLog << "Warning - cannot check file type, MRawRunHeader not found." << endl;
+  }
+  else
+      if (runheader->IsMonteCarloRun())
+          return kTRUE;
+  
+
+  // 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()
+{
+    for(UInt_t i=0;i<fCerPhot->GetNumPixels();i++)
+    {
+ 
+       const MCerPhotPix &pix = (*fCerPhot)[i];
+
+       const Float_t nphot = pix.GetNumPhotons();
+       
+       fSumx[i]  += nphot;
+       fSumx2[i] += 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-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCalc.h	(revision 3781)
@@ -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 MCerPhotEvt;
+class MBadPixelsCam;
+class MPedPhotCalc : public MTask
+{
+
+  MPedPhotCam   *fPedestals;  // Pedestals of all pixels in the camera
+  MCerPhotEvt   *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-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.cc	(revision 3781)
@@ -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, 12/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotCam
+//
+// Hold the Pedestal information for all pixels in the camera (in usints
+// of photons)
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.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);
+
+//    for (int i=0; i<577; i++)
+//        new ((*fArray)[i]) MPedPhotPix;
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the array conatining the pixel pedest information
+//
+MPedPhotCam::~MPedPhotCam()
+{
+    delete fArray;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the size of the camera
+//
+void MPedPhotCam::InitSize(const UInt_t i)
+{
+    fArray->ExpandCreate(i);
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the size of the MPedPhotCam
+//
+Int_t MPedPhotCam::GetSize() const
+{
+    return fArray->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)
+//
+MPedPhotPix &MPedPhotCam::operator[](Int_t i) const
+{
+    return *static_cast<MPedPhotPix*>(fArray->UncheckedAt(i));
+}
+
+/*
+// --------------------------------------------------------------------------
+//
+// Check if position i is inside bounds
+//
+Bool_t MPedPhotCam::CheckBounds(Int_t i)
+{
+    return i < fArray->GetEntriesFast();
+} 
+*/
+void MPedPhotCam::Clear(Option_t *o)
+{
+    fArray->ForEach(TObject, Clear)();
+}
+
+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;
+    }
+}
+/*
+Float_t MPedPhotCam::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 MPedPhotPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval < minval)
+            minval = testval;
+    }
+    return minval;
+}
+
+Float_t MPedPhotCam::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 MPedPhotPix &pix = (*this)[i];
+
+        Float_t testval = pix.GetPedestalRms();
+
+        if (geom)
+            testval *= geom->GetPixRatio(i);
+
+        if (testval > maxval)
+            maxval = testval;
+    }
+    return maxval;
+}
+*/
+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;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MPedPhotCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MPedPhotCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotCam.h	(revision 3781)
@@ -0,0 +1,47 @@
+#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 MPedPhotCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; // FIXME: Change TClonesArray away from a pointer?
+
+public:
+    MPedPhotCam(const char *name=NULL, const char *title=NULL);
+    ~MPedPhotCam();
+
+    void Clear(Option_t *o="");
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+    MPedPhotPix &operator[](Int_t i);
+    MPedPhotPix &operator[](Int_t i) const;
+
+    //    Float_t GetPedestalMin(const MGeomCam *cam) const;
+    //    Float_t GetPedestalMax(const MGeomCam *cam) const;
+
+    //    Bool_t CheckBounds(Int_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 num) const;
+
+    ClassDef(MPedPhotCam, 1)	// Storage Container for all pedestal information of the camera (in units of photons)
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.cc	(revision 3781)
@@ -0,0 +1,53 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MPedPhotPix
+//
+// This is the storage container to hold informations about the pedestal
+// (offset) value of one Pixel (PMT) in units of photons
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedPhotPix.h"
+
+#include "MLog.h"
+
+ClassImp(MPedPhotPix);
+
+MPedPhotPix::MPedPhotPix()
+{
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedPhotPix::Clear(Option_t *o)
+{
+    fMean = -1;
+    fRms  = -1;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedPhotPix.h	(revision 3781)
@@ -0,0 +1,32 @@
+#ifndef MARS_MPedPhotPix
+#define MARS_MPedPhotPix
+
+#ifndef ROOT_TObject
+#include <TObject.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
+
+public:
+    MPedPhotPix();
+
+    void Clear(Option_t *o="");
+
+    Float_t GetMean() const { return fMean; }
+    Float_t GetRms() const  { return fRms; }
+
+    //void SetMean(Float_t f) { fMean = f; }
+    void SetRms(Float_t f)  { fRms  = f; }
+    void Set(Float_t m, Float_t r) { fMean = m; fRms = r; }
+
+    Bool_t IsValid() const { return fRms>=0; }
+
+    ClassDef(MPedPhotPix, 1) // Storage Container for Pedestal information of one pixel in units of photons
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedestalCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCam.cc	(revision 3781)
@@ -0,0 +1,347 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalCam                                                            //
+//                                                                         //
+// Hold the Pedestal information for all pixels in the camera              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomCam.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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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::GetAverageAreas() 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::GetAverageSectors() 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)();
+  
+  //
+  // another ForEach does not compile, thus have to do the loop ourselves:
+  //
+  for (Int_t i=0;i<GetAverageAreas();i++)
+    fAverageAreas[i].Clear();
+
+
+  //
+  // another ForEach does not compile, thus have to do the loop ourselves:
+  //
+  for (Int_t i=0;i<GetAverageSectors();i++)
+    fAverageSectors[i].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;
+}
+
+Bool_t MPedestalCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+
+  if (GetSize() <= idx)
+    return kFALSE;
+
+  const Float_t ped      = (*this)[idx].GetPedestal();
+  const Float_t rms      = (*this)[idx].GetPedestalRms();
+
+  const Float_t pederr   = rms/TMath::Sqrt((Float_t)fTotalEntries);
+  const Float_t rmserr   = rms/TMath::Sqrt((Float_t)fTotalEntries)/2.;
+
+  switch (type)
+    {
+    case 0:
+      val = ped;
+      break;
+    case 1:
+      val = pederr;
+      break;
+    case 2:
+      val = rms;
+      break;
+    case 3:
+      val = rmserr;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+void MPedestalCam::DrawPixelContent(Int_t idx) const
+{
+  *fLog << warn << "MPedestalCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalCam.h	(revision 3781)
@@ -0,0 +1,64 @@
+#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 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="");
+  
+  // Getters 
+        MPedestalPix &GetAverageArea   ( UInt_t i );
+  const MPedestalPix &GetAverageArea   ( UInt_t i )            const;
+  const Int_t         GetAverageAreas  ()                      const;
+        MPedestalPix &GetAverageSector ( UInt_t i );
+  const MPedestalPix &GetAverageSector ( UInt_t i )            const;
+  const Int_t         GetAverageSectors()                      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; }
+  
+        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-8-4/MagicSoft/Mars/manalysis/MPedestalPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalPix.cc	(revision 3781)
@@ -0,0 +1,77 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MPedestalPix                                                            //
+//                                                                         //
+// This is the storage container to hold informations about the pedestal   //
+// (offset) value of one Pixel (PMT).                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MPedestalPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MPedestalPix);
+
+using namespace std;
+
+MPedestalPix::MPedestalPix()
+{
+  Clear();
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MPedestalPix::Clear(Option_t *o)
+{
+  fPedestal = -1.;
+  fPedestalRms = -1.;
+
+}
+
+void MPedestalPix::InitUseHists()
+{
+
+  fPedestal = 0.;
+  fPedestalRms = 0.;
+}
+
+
+void MPedestalPix::Set(Float_t m, Float_t r)
+{
+  fPedestal = m; 
+  fPedestalRms = r; 
+}
+
+Bool_t MPedestalPix::IsValid() const 
+{
+ return fPedestal>=0||fPedestalRms>=0;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalPix.h	(revision 3781)
@@ -0,0 +1,39 @@
+#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
+  
+public:
+  MPedestalPix();
+  
+  void Clear(Option_t *o="");
+  
+  // Using histograms
+  void InitUseHists();
+  
+    // Setters
+  void SetPedestal(const Float_t f)    { fPedestal = f; }
+  void SetPedestalRms(const Float_t f) { fPedestalRms = f; }
+  
+  void Set(const Float_t m, const Float_t r);
+  
+  // Getters
+  Float_t GetPedestal()    const { return fPedestal; }
+  Float_t GetPedestalRms() const { return fPedestalRms; }
+  
+  Bool_t IsValid()         const;
+
+  ClassDef(MPedestalPix, 1)	// Storage Container for Pedestal information of one pixel
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalSum.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalSum.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalSum.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedestalSum.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalSum.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalSum.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPedestalWorkaround.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPointingCorr.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPointingCorr.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPointingCorr.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MPointingCorr.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPointingCorr.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MPointingCorr.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MSigmabar.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabar.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabar.cc	(revision 3781)
@@ -0,0 +1,260 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 sigmas                                               //
+//                                                                         //
+// In calculating averages all sigmas are normalized to the area of pixel 0//
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#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/sqrt(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);
+
+        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 * sqrt(ratio);
+        }
+        else
+        {
+            outerPixels[sector]++;
+            outerSum[sector]+= sigma * sqrt(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 = fSumInner / fInnerPixels;
+    if (fOuterPixels > 0) fSigmabarOuter = fSumOuter / fOuterPixels;
+
+    //
+    // this is the average sigma/sqrt(area) (over all pixels)
+    //
+    fSigmabar = (fInnerPixels+fOuterPixels)<=0 ? 0:
+                (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 :       iss/ip;
+        fSigmabarOuterSector[i] = op <=0 ? 0 :       oss/op;
+        fSigmabarSector[i]      = sum<=0 ? 0 : (iss+oss)/sum;
+    }
+
+    //TString opt = "";
+    //Print(opt);
+
+  return fSigmabar;
+}
+
+// --------------------------------------------------------------------------
+//
+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-8-4/MagicSoft/Mars/manalysis/MSigmabar.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabar.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabar.h	(revision 3781)
@@ -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 ("average" RMS) of pedestal
+    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-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.cc	(revision 3781)
@@ -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
+//   MMcEvt  (FIXME: Must be replaced by a 'real-data' container)
+//   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 "MMcEvt.hxx"
+
+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("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
+    fMcEvt = (MMcEvt*)pList->FindObject(AddSerialNumber("MMcEvt"));
+    if (!fMcEvt)
+    {
+        *fLog << warn << "MMcEvt 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 (!fMcEvt)
+        return kTRUE;
+
+    const Double_t theta = fMcEvt->GetTelescopeTheta()*kRad2Deg;
+
+    if (theta>fSigmabarMax) fSigmabarMax=theta;
+    if (theta<fSigmabarMax) fSigmabarMin=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 (!fMcEvt)
+        return;
+
+    fThetaMin    = FLT_MAX;
+    fThetaMax    = 0;
+    fSigmabarMin = FLT_MAX;
+    fSigmabarMax = 0;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarCalc.h	(revision 3781)
@@ -0,0 +1,64 @@
+#ifndef MARS_MSigmabarCalc
+#define MARS_MSigmabarCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef MARS_MGeomCam
+#include "MGeomCam.h"
+#endif
+
+#ifndef MARS_MMcEvt
+#include "MMcEvt.hxx"
+#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:
+    MMcEvt         *fMcEvt;
+    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;
+
+    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);
+
+    ClassDef(MSigmabarCalc, 0) // task for calculating sigmabar
+}; 
+
+#endif
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSigmabarParam.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.cc	(revision 3781)
@@ -0,0 +1,865 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 "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;
+    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;
+    }
+
+
+   fMcEvt = (MMcEvt*)pList->FindCreateObj("MMcEvt");
+   if (!fMcEvt)
+   {
+       *fLog << err << "MSourcePosfromStarPos::PreProcess; MMcEvt not found... aborting." << endl;
+       return kFALSE;
+   }
+
+
+    fSrcPos = (MSrcPosCam*)pList->FindObject(AddSerialNumber("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)
+{
+  //if (1 == 1) return kTRUE;
+
+
+  Int_t run = fRun->GetRunNumber();
+  *fLog << all << "MSourcePosfromStarPos::ReInit; run = " << run << endl;
+
+
+  //-------------------------------------------------------------------
+  // search this run in the list 
+  for (Int_t i=0; i<fSize; i++)
+  {
+    if (run == fRunNr[i])
+    {
+      //-----------------------------------------
+      // put the zenith angle into MMcEvt
+
+      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;
+
+      fMcEvt->SetTelescopeTheta(thetarad);
+      fMcEvt->SetTelescopePhi(phirad);
+      fMcEvt->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;
+    fMcEvt->SetTelescopeTheta(thetarad);
+
+    Double_t phirad = fPhiradold;
+    fMcEvt->SetTelescopePhi(phirad);
+    fMcEvt->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;
+  *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-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSourcePosfromStarPos.h	(revision 3781)
@@ -0,0 +1,127 @@
+#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 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;    //!
+    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-8-4/MagicSoft/Mars/manalysis/MSupercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MSupercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.cc	(revision 3781)
@@ -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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   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 "MCerPhotEvt.h"
+#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-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/MSupercutsCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/manalysis/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/manalysis/Makefile	(revision 3781)
@@ -0,0 +1,100 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Analysis
+
+#
+# Library name to creatre
+#
+LIB   = manalysis.a
+
+#
+#  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
+# mcalib: MGeomApply (MCalibrationCam)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MPedestalPix.cc \
+           MHPedestalPix.cc \
+           MPedestalCam.cc \
+           MHPedestalCam.cc \
+           MPedPhotPix.cc \
+           MPedPhotCam.cc \
+           MPedCalcPedRun.cc \
+           MPedPhotCalc.cc \
+           MMcPedestalCopy.cc \
+           MMcPedestalNSBAdd.cc \
+           MGeomApply.cc \
+           MCameraData.cc \
+           MEnergyEst.cc \
+           MEnergyEstimate.cc \
+           MEnergyEstParam.cc \
+           MEnergyEstParamDanielMkn421.cc \
+           MHadronness.cc \
+           MMatrixLoop.cc \
+           MCompProbCalc.cc \
+           MMultiDimDistCalc.cc \
+	   MCerPhotPix.cc \
+	   MCerPhotEvt.cc \
+           MCerPhotAnal.cc \
+           MCerPhotAnal2.cc \
+	   MCerPhotCalc.cc \
+           MBlindPixels.cc \
+           MBlindPixelCalc.cc \
+           MBlindPixelsCalc2.cc \
+           MEventRate.cc \
+           MEventRateCalc.cc \
+	   MSigmabar.cc \
+	   MSigmabarParam.cc \
+	   MSigmabarCalc.cc \
+	   MCT1PadSchweizer.cc \
+	   MCT1PointingCorrCalc.cc \
+           MParameters.cc \
+	   MMcTriggerLvl2.cc \
+	   MMcTriggerLvl2Calc.cc \
+           MCT1Supercuts.cc \
+           MCT1SupercutsCalc.cc \
+           MCT1FindSupercuts.cc \
+           MSupercuts.cc \
+           MSupercutsCalc.cc \
+           MFindSupercuts.cc \
+           MMinuitInterface.cc \
+           MFiltercutsCalc.cc \
+           MCT1PadONOFF.cc  \
+           MPad.cc  \
+           MPedestalWorkaround.cc \
+           MSourcePosfromStarPos.cc \
+           MMcCalibrationUpdate.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mars.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mars.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mars.cc	(revision 3781)
@@ -0,0 +1,147 @@
+#include <TApplication.h>
+
+#include "MAGIC.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMars.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 MMars;
+
+    //
+    // run the application
+    //
+    app.Run();
+
+    gLog << all << endl;
+
+    return 0;
+}
+ 
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/marslogo.xpm
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/marslogo.xpm	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/marslogo.xpm	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mastro/AstroIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/AstroIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/AstroIncl.h	(revision 3781)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/AstroLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/AstroLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/AstroLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mastro/MAstro.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstro.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstro.cc	(revision 3781)
@@ -0,0 +1,406 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+
+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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstro.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstro.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstro.h	(revision 3781)
@@ -0,0 +1,59 @@
+#ifndef MARS_MAstro
+#define MARS_MAstro
+
+#ifndef ROOT_TROOT
+#include <TROOT.h>
+#endif
+
+class MAstro
+{
+private:
+    static Double_t Round(Double_t val);
+    static Double_t Trunc(Double_t val);
+
+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 rad, Char_t &sgn, UShort_t &deg, 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 &deg, UShort_t &min, UShort_t &sec);
+    static void Deg2Dms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Deg2Hms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Hor2Dms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+    static void Hor2Hms(Double_t rad, Char_t &sgn, UShort_t &deg, UShort_t &min, UShort_t &sec);
+
+    static void Day2Hm(Double_t rad, Char_t &sgn, UShort_t &deg, 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 &deg, Double_t &min);
+    static void Deg2Dm(Double_t rad, Char_t &sgn, UShort_t &deg, Double_t &min);
+    static void Deg2Hm(Double_t rad, Char_t &sgn, UShort_t &deg, 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 &deg, 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 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);
+
+    ClassDef(MAstro, 0)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCamera.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCamera.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCamera.cc	(revision 3781)
@@ -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, 3/2004 <mailto:tbretz@astro.uni-wuerzburg.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 caluclation 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 <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?
+
+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));
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+//
+// If the Pad contains an object MHCamera of type MHCamera it is used.
+// Otherwise a new object is created.
+//
+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);
+
+    // 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();
+
+        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(kMagenta);
+                m->SetMarkerStyle(kDot);
+                AddMap(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, Form("x=%.1fmm y=%.1fmm", mean(0), mean(1)));
+
+        if (hasnull)
+        {
+            TVector3 star(*radec);
+            star *= rot;
+            const TVector3 spot = fMirror0->GetReflection(star, fGeom->GetCameraDist())*1000;
+            DrawStar(spot(0), spot(1), *radec, !hasmean, Form("x=%.1fmm y=%.1fmm", mean(0), mean(1)));
+        }
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// Execute a gui event on the camera
+//
+void MAstroCamera::ExecuteEvent(Int_t event, Int_t mp1, Int_t mp2)
+{
+    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-8-4/MagicSoft/Mars/mastro/MAstroCamera.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCamera.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCamera.h	(revision 3781)
@@ -0,0 +1,38 @@
+#ifndef MARS_MAstroCamera
+#define MARS_MAstroCamera
+
+#ifndef MARS_MAstroCatalog
+#include "MAstroCatalog.h"
+#endif
+
+class TClonesArray;
+
+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 SetGeom(const MGeomCam &cam);
+
+    ClassDef(MAstroCamera, 1) // Display class to display stars on the camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCatalog.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCatalog.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCatalog.cc	(revision 3781)
@@ -0,0 +1,1223 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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, 2002-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MAstroCatalog
+//  =============
+//
+//  THIS IMPLEMENTATION IS PRELIMINARY AND WILL BE MERGED WITH
+//  SOME PARTS OF THE DRIVE SOFTWARE SOON!
+//
+//
+//  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)
+//
+//////////////////////////////////////////////////////////////////////////////
+#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 "MAstro.h"
+#include "MAstroSky2Local.h"
+#include "MObservatory.h"
+
+#undef DEBUG
+//#define DEBUG
+
+#ifdef DEBUG
+#include <TStopwatch.h>
+#endif
+
+ClassImp(MVector3);
+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();
+    fToolTip = 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;
+
+    fToolTip->Hide();
+    delete fToolTip;
+
+    DeleteMap();
+}
+
+// --------------------------------------------------------------------------
+//
+// Snippet to for reading ctalog 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)
+{
+    SetBit(kHasChanged);
+
+    gLog << inf << "Reading Xephem catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open 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;
+
+        MVector3 *star=new MVector3;
+        star->SetRaDec(ra0, dec0, mag);
+        star->SetName(name);
+        if (star->Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+        {
+            delete star;
+            continue;
+        }
+
+        fList.Add(star);
+        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)
+{
+    SetBit(kHasChanged);
+
+    gLog << inf << "Reading NGC2000 catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open 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);
+
+        MVector3 *star=new MVector3;
+        star->SetRaDec(ra, dec, mag);
+        star->SetName(row(0, 8));
+        if (star->Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+        {
+            delete star;
+            continue;
+        }
+
+        fList.Add(star);
+        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)
+{
+    SetBit(kHasChanged);
+
+    gLog << inf << "Reading Bright Star Catalog (BSC5) catalog: " << catalog << endl;
+
+    ifstream fin(catalog);
+    if (!fin)
+    {
+        gLog << err << "Cannot open 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);
+
+        MVector3 *star=new MVector3;
+        star->SetRaDec(ra, dec, mag);
+        star->SetName(row(4,9));
+        if (star->Angle(fRaDec)*TMath::RadToDeg()>fRadiusFOV)
+        {
+            delete star;
+            continue;
+        }
+
+        fList.Add(star);
+        add++;
+    }
+
+    gLog << inf << "Read " << add << " out of " << n << " (Total max mag=" << maxmag << ")" << endl;
+
+    return add;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    PaintMap();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+// transparent: Draw marker or tooltip only
+// txt: additional tooltip text
+//
+void MAstroCatalog::DrawStar(Double_t x, Double_t y, const TVector3 &v, Bool_t transparent, const char *txt)
+{
+    const Double_t ra  = v.Phi()*TMath::RadToDeg()/15;
+    const Double_t dec = (TMath::Pi()/2-v.Theta())*TMath::RadToDeg();
+
+    TString str = v.GetName();
+    str += Form(":  Ra=%.2fh", ra);
+    str += Form("  Dec=%.1fd", dec);
+    str += Form("  Mag=%.1f", -2.5*log10(v.Mag()));
+    if (txt)
+        str += Form("  (%s)", txt);
+
+    // draw star on the camera display
+    TMarker *tip=new TMarker(x, y, transparent ? kDot : kFullDotMedium);;
+    tip->SetMarkerColor(kBlack);
+    AddMap(tip, new TString(str));
+}
+
+// --------------------------------------------------------------------------
+//
+// Set pad as modified.
+//
+void MAstroCatalog::Update(Bool_t upd)
+{
+    if (gPad && TestBit(kMustCleanup))
+    {
+        SetBit(kHasChanged);
+        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=(MObservatory*)obs.Clone();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    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, Double_t dx, Double_t dy, const TRotation &rot, Int_t type)
+{
+    const TVector2 add(dx*TMath::DegToRad(), dy*TMath::DegToRad());
+
+    TVector2 v0 = v;
+    TVector2 v1 = v+add;
+
+    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);
+    AddMap(line);
+
+    const TVector2 deg = v*TMath::RadToDeg();
+    TString txt = type==1 ?
+        Form("Ra=%.2fh  Dec=%.1fd", fmod(deg.X()/15+48, 24),  fmod(90-deg.Y()+270,180)-90) :
+        Form("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);
+    AddMap(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.
+//
+//
+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;
+
+    // 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);
+    TVector3 *v=0;
+    while ((v=(TVector3*)Next()))
+    {
+        // FIXME: Check Magnitude!
+        TVector2 s(v->Phi(), v->Theta());
+        if (Convert(rot, s)==kTRUE)
+            DrawStar(s.X(), s.Y(), *v, kFALSE);
+    }
+
+    if (!same)
+    {
+        TPaveText *pv = new TPaveText(0.01, 0.90, 0.63, 0.99, "brNDC");
+        pv->AddText(GetPadTitle());
+        AddMap(pv);
+    }
+
+    TMarker *mk=new TMarker(0, 0, kMultiply);
+    mk->SetMarkerColor(kBlack);
+    mk->SetMarkerSize(1.5);
+    AddMap(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)
+{
+    DeleteMap();
+
+    SetRangePad(o);
+
+#ifdef DEBUG
+    TStopwatch clk;
+    clk.Start();
+#endif DEBUG
+    AddPrimitives(o);
+#ifdef DEBUG
+    clk.Stop();
+    clk.Print();
+#endif DEBUG
+
+    // Append to a possible second pad
+    if (!gPad->GetListOfPrimitives()->FindObject(this))
+        AppendPad(o);
+
+    ResetBit(kHasChanged);
+}
+
+// --------------------------------------------------------------------------
+//
+// Call Paint() of all gui elements
+//
+void MAstroCatalog::PaintMap()
+{
+    Long_t key, val;
+    TExMapIter map(&fMapG);
+    while (map.Next(key, val))
+        ((TObject*)key)->Paint();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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*)");
+}
+
+// --------------------------------------------------------------------------
+//
+// Search for an object at px, py in fMapG. Return the pointer to it
+// if found. Set str accordingly if a tooltip string is found.
+//
+TObject *MAstroCatalog::PickObject(Int_t px, Int_t py, TString &str) const
+{
+    Long_t key, val;
+    TExMapIter map(&fMapG);
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 = 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;
+
+    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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate distance to primitive by checking all gui elements
+//
+Int_t MAstroCatalog::DistancetoPrimitive(Int_t px, Int_t py)
+{
+    Int_t min = INT_MAX;
+
+    Long_t key, val;
+    TExMapIter map(&fMapG);
+    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 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);
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+{
+
+    TString str;
+    PickObject(px, py, str);
+
+    static char txt[129];
+    txt[128]=0;
+
+    return strncpy(txt, str.Data(), 128);
+}
+
+
+/*
+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-8-4/MagicSoft/Mars/mastro/MAstroCatalog.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCatalog.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroCatalog.h	(revision 3781)
@@ -0,0 +1,208 @@
+#ifndef MARS_MAstroCatalog
+#define MARS_MAstroCatalog
+
+#ifndef ROOT_TVector3
+#include <TVector3.h>
+#endif
+#ifndef ROOT_TExMap
+#include <TExMap.h>
+#endif
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+class MTime;
+class MObservatory;
+class TArrayI;
+class TGToolTip;
+
+class MVector3 : public TVector3
+{
+private:
+    enum VectorType_t
+    {
+        kIsInvalid,
+        kIsRaDec,
+        kIsZdAz,
+        kIsAltAz,
+        kIsArbitrary
+    };
+
+    VectorType_t fType;
+
+    TString fName;
+
+public:
+    MVector3() { fType=kIsInvalid; }
+    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)
+    {
+        fType = kIsRaDec;
+        SetMagThetaPhi(pow(10, -mag/2.5), TMath::Pi()/2-dec, ra);
+    }
+    void SetName(const TString &str) { fName = str.Strip(TString::kBoth); }
+    void SetZdAz(Double_t zd, Double_t az, Double_t mag)
+    {
+        fType = kIsZdAz;
+        SetMagThetaPhi(pow(10, -mag/2.5), zd, az);
+    }
+    void SetAltAz(Double_t alt, Double_t az, Double_t mag)
+    {
+        fType = kIsAltAz;
+        SetMagThetaPhi(pow(10, -mag/2.5), TMath::Pi()/2-alt, az);
+    }
+
+    const char *GetName() const { return fName; }
+
+    ClassDef(MVector3, 1) // A specialized TVector3 storeing a star-name
+};
+
+class MAstroCatalog : public TObject
+{
+private:
+    Double_t   fLimMag;    // [1]   Limiting Magnitude
+    Double_t   fRadiusFOV; // [deg] Radius of Field of View
+
+    TExMap     fMapG;      //! A map with all gui primitives and tooltips
+    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)
+//#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, Double_t dx, Double_t dy, const TRotation &rot, Int_t type);
+    void      DrawGrid(const TVector3 &v0, const TRotation &rot, Int_t type);
+    TRotation AlignCoordinates(const TVector3 &v) const;
+    void      Paint(Option_t *o="");
+    Int_t     DistancetoPrimitive(Int_t px, Int_t py);
+    //void      RecursiveRemove(TObject *obj);
+    void      PaintMap();
+    void      DeleteMap()
+    {
+        Long_t key, val;
+        TExMapIter map(&fMapG);
+        while (map.Next(key, val))
+        {
+            delete (TObject*)(key);
+            if (!val)
+                continue;
+
+            delete (TString*)(val);
+            /*
+              Long_t key2, val2;
+              TExMapIter map2(&fMapG);
+              while (map2.Next(key2, val2))
+                  if (val==val2)
+                  {
+                      delete (TObject*)key;
+                      fMapG.Remove(key);
+                  }
+             */
+        }
+        fMapG.Delete();
+    }
+
+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
+    };
+
+    TList    fList;             // List of stars loaded
+    MVector3 fRaDec;            // pointing position
+
+    MObservatory *fObservatory; // Possible obervatory location
+    MTime        *fTime;        // Possible observation time
+
+    virtual TString GetPadTitle() const;
+    TRotation GetGrid(Bool_t local);
+    void      DrawStar(Double_t x, Double_t y, const TVector3 &v, Bool_t t, const char *txt=0);
+    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);
+    TObject  *PickObject(Int_t px, Int_t py, TString &str) const;
+    char     *GetObjectInfo(Int_t px, Int_t py) const;
+
+    void AddMap(TObject *k, void *v=0)
+    {
+        fMapG.Add(fMapG.GetSize(), (Long_t)k, (Long_t)v);
+    }
+
+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 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(); DeleteMap(); } // 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");
+
+    void Print(Option_t *o="") const { fList.Print(); } // Print all stars
+
+    TList *GetList() { return &fList; } // Return list of stars
+
+    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-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MAstroSky2Local.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mastro/MObservatory.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MObservatory.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MObservatory.cc	(revision 3781)
@@ -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): 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 20h)
+        // on 26/11/2003 at 17h30 in the counting house
+        fLatitude  = MAstro::Dms2Rad(28, 45, 42.576, '+');
+        fLongitude = MAstro::Dms2Rad(17, 53, 26.460, '-');
+        fHeight    = 2196.5; // 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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MObservatory.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MObservatory.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/MObservatory.h	(revision 3781)
@@ -0,0 +1,66 @@
+#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 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; }
+
+    ClassDef(MObservatory, 0) // class storing observatory locations
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mastro/Makefile	(revision 3781)
@@ -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  = Astro
+
+#
+# Library name to creatre
+#
+LIB   = mastro.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgeom
+
+# mgeom (MAstroCamera): MGeomCam, MGeomMirror
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MAstro.cc \
+	   MAstroSky2Local.cc \
+	   MAstroCatalog.cc \
+           MAstroCamera.cc \
+           MObservatory.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/BadPixelsLinkDef.h	(revision 3781)
@@ -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 MBadPixelsPix+;
+#pragma link C++ class MBadPixelsCam+;
+
+#pragma link C++ class MBadPixelsCalc+;
+#pragma link C++ class MBadPixelsTreat+;
+#pragma link C++ class MBadPixelsMerge+;
+
+#pragma link C++ class MMcBadPixelsSet+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.cc	(revision 3781)
@@ -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): 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 (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);
+//
+//
+//  Input Containers:
+//   [MPedPhotCam]
+//   [MGeomCam]
+//   [MSigmabar]
+//
+//  Output Containers:
+//   MBadPixels
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsCalc.h"
+
+#include <TArrayD.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)
+{
+    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("MPedPhotCam"));
+        if (!fPedPhotCam)
+        {
+            *fLog << err << "MPedPhotCam not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+        if (!fGeomCam)
+        {
+            *fLog << err << "MGeomCam not found... aborting." << endl;
+            return kFALSE;
+        }
+
+        fSigmabar = (MSigmabar*)pList->FindObject(AddSerialNumber("MSigmabar"));
+        if (!fSigmabar)
+        {
+            *fLog << err << "MSigmabar not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+    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();
+
+    TArrayD meanrms(na);
+    TArrayI 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;
+    }
+
+    TArrayD meanrms2(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;
+        npix[aidx]++;
+    }
+
+    //if no pixel has a minimum signal, return
+    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];
+    }
+
+    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 (rms>meanrms2[aidx]/3 && rms<=meanrms2[aidx]*3)
+            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)
+        CheckPedestalRms();
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCalc.h	(revision 3781)
@@ -0,0 +1,42 @@
+#ifndef MARS_MBadPixelsCalc
+#define MARS_MBadPixelsCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MBadPixelsCam;
+class MSigmabar;
+class MGeomCam;
+class MPedPhotCam;
+
+class MBadPixelsCalc : public MTask
+{
+private:
+    MGeomCam      *fGeomCam;    //! Input container storing the pixel sizes
+    MSigmabar     *fSigmabar;   //! Input container storing mean pedestal rms of the camera
+    MPedPhotCam   *fPedPhotCam; //! Input container storing the pedestal and pedestal rms of all pixels
+
+    MBadPixelsCam *fBadPixels;  //! Output container holding the bad pixels
+
+    Float_t fPedestalLevel;
+
+    void CheckPedestalRMS() const;
+    Bool_t CheckPedestalRms() const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+public:
+    MBadPixelsCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetPedestalLevel(Float_t f) { fPedestalLevel=f; }
+
+    ClassDef(MBadPixelsCalc, 1) // Task to find bad pixels (star, broken pixels, etc)
+}; 
+
+#endif
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.cc	(revision 3781)
@@ -0,0 +1,404 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <fstream>
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MBadPixelsPix.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(*fArray);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)();
+}
+
+// --------------------------------------------------------------------------
+//
+// Print the contents of all bad pixels
+//
+void MBadPixelsCam::Print(Option_t *o) const
+{
+    *fLog << all << GetDescriptor() << ":" << endl;
+    
+    *fLog << "Pixels without problems:" << endl;
+    *fLog << endl;
+
+    Int_t count = 0;
+
+    for (Int_t i=0; i<GetSize(); i++)
+    {
+        if (!(*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+            *fLog << i << " ";
+            count ++;
+        }
+
+        if (count == 0)
+            continue;
+
+        if (!(count % 25))
+            *fLog << endl;
+    }
+    *fLog << endl;
+    *fLog << count << " normal pixels :-))" << endl;
+    *fLog << endl;
+    count = 0;
+
+
+    *fLog << "Pixels unsuited for the whole run:" << endl;
+    *fLog << endl;
+
+    for (Int_t i=0; i<GetSize(); i++)
+    {
+        if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+            *fLog << i << " ";
+            count ++;
+        }
+
+        if (count == 0)
+            continue;
+
+        if (!(count % 25))
+            *fLog << endl;
+    }
+    *fLog << endl;
+    *fLog << count << " unsuited pixels :-(" << endl;
+    *fLog << endl;
+
+    count = 0;
+
+    *fLog << all << "Pixels unreliable for the whole run:" << endl;
+    *fLog << all << endl;
+
+    for (Int_t i=0; i<GetSize(); i++)
+    {
+        if ((*this)[i].IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        {
+            *fLog << i << " ";
+            count ++;
+        }
+
+        if (count == 0)
+            continue;
+
+        if (!(count % 25))
+          *fLog << endl;
+    }
+
+    *fLog << endl;
+    *fLog << count << " unreliable pixels :-(" << endl;
+    *fLog << 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(ifstream &fin, UInt_t run=0)
+{
+    Int_t len;
+    TString str;
+
+    while (1)
+    {
+        str.ReadLine(fin);
+        if (!fin)
+            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::IsCalibrationSignalOK()
+// 7: !MBadPixelsPix::IsCalibrationResultOK();
+// 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  )
+//
+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:
+      return (*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableRun);
+    case 2:
+      return (*this)[idx].IsUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+    case 3:
+      return (*this)[idx].IsUnsuitable(MBadPixelsPix::kUnreliableRun);
+    case 4:
+      return (*this)[idx].IsHiGainBad();
+    case 5:
+      return (*this)[idx].IsLoGainBad();
+    case 6:
+      return !(*this)[idx].IsCalibrationSignalOK();
+    case 7:
+      return !(*this)[idx].IsCalibrationResultOK(); 
+    case 8:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainNotFitted);
+    case 9:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainNotFitted);
+    case 10:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kHiGainOscillating);
+    case 11:
+      return(*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainOscillating);
+    case 12:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kLoGainSaturation );
+    case 13:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeIsPedestal );
+    case 14:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeErrNotValid);
+    case 15:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeRelErrNotValid);
+    case 16:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kChargeSigmaNotValid );
+    case 17:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInFirstBin  );
+    case 18:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kMeanTimeInLast2Bins );
+    case 19:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kDeviatingNumPhes    );
+    case 20:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeNotFitted );
+    case 21:
+      return (*this)[idx].IsUncalibrated(MBadPixelsPix::kRelTimeOscillating  );
+    default:
+      return kFALSE;
+    }
+  
+  return kFALSE;
+}
+
+void MBadPixelsCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MBadPixelsCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsCam.h	(revision 3781)
@@ -0,0 +1,48 @@
+#ifndef MARS_MBadPixelsCam
+#define MARS_MBadPixelsCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+class MBadPixelsPix;
+
+class MBadPixelsCam : public MParContainer, public MCamEvent
+{
+private:
+    TClonesArray *fArray; //-> 
+
+public:
+    MBadPixelsCam(const char *name=NULL, const char *title=NULL);
+    MBadPixelsCam(const MBadPixelsCam &cam);
+    ~MBadPixelsCam();
+
+    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);
+
+    void   AsciiRead(ifstream &fin, UInt_t run);
+    void   AsciiRead(ifstream &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-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.cc	(revision 3781)
@@ -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 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.
+//
+//
+//  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-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsMerge.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.cc	(revision 3781)
@@ -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): 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:
+// BIT(1 ): kHiGainNotCalibrated :  Any High Gain signal is not calibrated and cannot be used
+// BIT(2 ): kLoGainNotCalibrated :  Any Low  Gain signal is not calibrated and cannot be used
+// BIT(3 ): kHiGainNotFitted     :  Any High Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(4 ): kLoGainNotFitted     :  Any Low  Gain signal is calibrated without a Gauss Fit to the signal distribution
+// BIT(5 ): kHiGainOscillating   :  The High Gain signals fourier transform showed abnormal behavior  
+// BIT(6 ): kLoGainOscillating   :  The Low  Gain signals fourier transform showed abnormal behavior  
+// BIT(7 ): kLoGainSaturation    :  The Low  Gain signals were saturated during calibration
+// BIT(8 ): kChargeIsPedestal    :  The calibration signal contained only pedestals - presumably dead pixel
+// 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(14): kDeviatingNumPhes    :  The calculated number of photo-electrons deviates too much from the mean - inconsitency
+//
+// 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.
+//
+// Two additional functions yield specific calibration information:
+// * IsCalibrationSignalOK() asks if the extracted calibration signal showed any inconsistency
+// * IsCalibrationResultOK() asks if the applied calibration can be used at all.
+//
+/////////////////////////////////////////////////////////////////////////////
+#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)
+    : fInfo(5)
+{
+    fName  = name  ? name  : "MBadPixelsPix";
+    fTitle = title ? title : "Container storing bad pixel information for a single pixel";
+
+    fInfo[1] = 0;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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
+ */
+
+/*
+ MCalibrationCalc - valid for the result of a calibration run:
+
+      3  Hi-Gain saturated, no LoGain available
+
+      4  Conversion Factor HiGain - LoGain not valid
+
+      5  Cannot be calibrated at all
+      6  Cannot be fitted - calibrated using Histogram Mean and RMS
+
+     */
+
+/*
+
+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?)
+
+In addition here are some cases which I think can be detected by software:
+- no signal
+- wrong signal
+- hv problem
+- dc problem
+- Conversion Factor HiGain - LoGain not valid (what does this mean?)
+- No calibration possible
+- No fit possible - calibrated using Histogram Mean and RMS
+- Mean Charge smaller than PedRMS
+- Sigma Charge smaller than PedRMS
+- Calib.methods inconsistency (there are in pricipal 6 combinations... do we need 6 bits?)
+- Gains oscillate (what does it mean?)
+- Sigma  Arrival Time  bigger than  FADC window (from calib)
+- Mean   Arrival Time  at edge of   FADC window (from calib)
+*/
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsPix.h	(revision 3781)
@@ -0,0 +1,94 @@
+#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),
+        kUnreliableRun = BIT(3)
+    };
+
+    static const Int_t fgRunMask; // All types which are not event wise determined
+
+    // All types are initialized to normal behaviour
+    enum UncalibratedType_t {
+      kHiGainNotCalibrated      = BIT(1),
+      kLoGainNotCalibrated      = BIT(2), 
+      kHiGainNotFitted          = BIT(3),
+      kLoGainNotFitted          = BIT(4), 
+      kRelTimeNotFitted         = BIT(5),
+      kHiGainOscillating        = BIT(6),
+      kLoGainOscillating        = BIT(7),
+      kRelTimeOscillating       = BIT(8),
+      kLoGainSaturation         = BIT(9),
+      kChargeIsPedestal         = BIT(10),
+      kChargeErrNotValid        = BIT(11),
+      kChargeRelErrNotValid     = BIT(12),
+      kChargeSigmaNotValid      = BIT(13),
+      kMeanTimeInFirstBin       = BIT(14),
+      kMeanTimeInLast2Bins      = BIT(15), 
+      kDeviatingNumPhes         = BIT(16)
+    };
+    
+    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; }
+
+    // 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 IsOK() const  { return fInfo[0]==0; }
+    Bool_t IsBad() const { return fInfo[0]!=0; }
+
+    Bool_t IsLoGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+				     || IsUncalibrated(kLoGainSaturation   ) 
+				     || IsUncalibrated(kLoGainNotCalibrated) 
+				     || IsUncalibrated(kLoGainOscillating  ) ; }
+    Bool_t IsHiGainBad() const { return IsUnsuitable  (kUnsuitableRun      )
+				     || IsUncalibrated(kHiGainNotCalibrated) 
+  				     || IsUncalibrated(kHiGainOscillating  ) ; }
+
+    Bool_t IsCalibrationSignalOK() const  { return !( IsUncalibrated(kChargeIsPedestal    )
+					           || IsUncalibrated(kChargeErrNotValid   )
+					           || IsUncalibrated(kChargeRelErrNotValid)
+					           || IsUncalibrated(kChargeSigmaNotValid )
+					           || IsUncalibrated(kMeanTimeInFirstBin  )
+ 					           || IsUncalibrated(kMeanTimeInLast2Bins )  );  }
+
+    Bool_t IsCalibrationResultOK() const  {  return  !IsUnsuitable(kUnsuitableRun) 
+					          &&  IsCalibrationSignalOK()
+                                                  && !IsHiGainBad()
+					          && !IsLoGainBad() ; }
+
+    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-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.cc	(revision 3781)
@@ -0,0 +1,562 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   MPedPhotCam
+//   MBadPixelsCam
+//   [MGeomCam]
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MBadPixelsTreat.h"
+
+#include <fstream>
+
+#include <TArrayD.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedPhotPix.h"
+#include "MPedPhotCam.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.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();
+}
+
+// --------------------------------------------------------------------------
+//
+//  - Try to find or create MBlindPixels in parameter list.
+//  - get the MCerPhotEvt 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 << "MBadPixelsCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPedPhot = (MPedPhotCam*)pList->FindObject(AddSerialNumber("MPedPhotCam"));
+    if (!fPedPhot)
+    {
+        *fLog << err << "MPedPhotCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    
+    fEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fEvt)
+    {
+        *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fGeomCam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fGeomCam && TESTBIT(fFlags, kUseInterpolation))
+    {
+        *fLog << err << "MGeomCam not found... can't use interpolation." << endl;
+        return kFALSE;
+    }
+
+    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
+    //
+    TArrayD nphot(entries);
+    TArrayD perr(entries);
+ 
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        MCerPhotPix *pix = fEvt->GetPixById(i);
+
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (pix && (*fBadPixels)[i].IsOK())
+            continue;
+
+        //
+        // Get a pointer to this pixel. If it is not yet existing
+        // create a new entry for this pixel in MCerPhotEvt
+        //
+        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 ((*fBadPixels)[i].IsBad())
+                continue;
+
+            //
+            // Check whether the neighbor has a signal stored
+            //
+            const MCerPhotPix *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++;
+        }
+
+        //
+        // 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));
+ 
+	// 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<3)
+        {
+            pix->SetPixelUnmapped();
+            continue;
+        }
+
+        pix->Set(nphot[i], perr[i]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+void MBadPixelsTreat::InterpolatePedestals() const
+{
+    const Int_t entries = fPedPhot->GetSize();
+
+    TArrayD ped(entries);
+    TArrayD rms(entries);
+
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if ((*fBadPixels)[i].IsOK())
+            continue;
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix    &gpix = (*fGeomCam)[i];
+        const MPedPhotPix &ppix = (*fPedPhot)[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 ((*fBadPixels)[i].IsBad())
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t    nratio = fGeomCam->GetPixRatio(nidx);
+            const MPedPhotPix &nppix = (*fPedPhot)[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)
+        {
+            MCerPhotPix *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));
+
+        (*fPedPhot)[i].Set(ped[i], rms[i]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  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.
+//
+//  NT: Informations about the interpolated pedestals are added. 
+//      When the option Interpolated is called, the blind pixel with the new
+//      values of signal and fluttuation is included in the calculation of
+//      the Image Parameters.
+//
+void MBadPixelsTreat::Interpolate() const
+{
+    const UShort_t entries = fGeomCam->GetNumPixels();
+
+    //
+    // Create arrays
+    //
+    TArrayD nphot(entries);
+    TArrayD perr(entries);
+    TArrayD ped(entries);
+    TArrayD pedrms(entries);
+ 
+    //
+    // Loop over all pixels
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        MCerPhotPix *pix = fEvt->GetPixById(i);
+
+        //
+        // Check whether pixel with idx i is blind
+        //
+        if (pix && (*fBadPixels)[i].IsOK())
+            continue;
+
+        //
+        // Get a pointer to this pixel. If it is not yet existing
+        // create a new entry for this pixel in MCerPhotEvt
+        //
+        if (!pix)
+        {
+            pix = fEvt->AddPixel(i, 0, 0);
+            (*fBadPixels)[i].SetUnsuitable(MBadPixelsPix::kUnsuitableEvt);
+        }
+
+        //
+        // Get the corresponding geometry and pedestal
+        //
+        const MGeomPix &gpix    = (*fGeomCam)[i];
+        const MPedPhotPix &ppix = (*fPedPhot)[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();
+        ped[i]    = nucp ? 0 : ppix.GetMean();
+        perr[i]   = nucp ? 0 : Pow2(pix->GetErrorPhot());
+        pedrms[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);
+
+        if (nucp)
+        {
+            nphot[i]  *= ratio;
+            perr[i]   *= ratio;
+            ped[i]    *= ratio;
+            pedrms[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 ((*fBadPixels)[nidx].IsBad())
+                continue;
+
+            //
+            // Check whether the neighbor has a signal stored
+            //
+            const MCerPhotPix *evtpix = fEvt->GetPixById(nidx);
+            if (!evtpix)
+                continue;
+
+            //
+            // Get the geometry for the neighbor
+            //
+            const Double_t nratio = fGeomCam->GetPixRatio(nidx);
+            MPedPhotPix &nppix    = (*fPedPhot)[nidx];
+
+            //
+	    // The error is calculated as the quadratic sum of the errors
+	    //
+            nphot[i]  += nratio*evtpix->GetNumPhotons();
+            ped[i]    += nratio*nppix.GetMean();
+            perr[i]   += nratio*Pow2(evtpix->GetErrorPhot());
+	    pedrms[i] += nratio*Pow2(nppix.GetRms());
+
+            num++;
+        }
+
+        if (num<2)
+        {
+            pix->SetPixelUnmapped();
+            nphot[i]  = 0;
+            ped[i]    = 0;
+            perr[i]   = 0;
+            pedrms[i] = 0;
+            continue;
+        }
+
+        //
+	// Now the mean is calculated and the values rescaled back to the pixel area
+        //
+	nphot[i] /= num*ratio;
+        ped[i]   /= num*ratio;
+        perr[i]   = TMath::Sqrt(perr[i]/(num*ratio));
+        pedrms[i] = TMath::Sqrt(pedrms[i]/(num*ratio));
+
+    }
+
+    //
+    // Now the new pixel values are calculated and can be replaced in
+    // the corresponding containers
+    //
+    for (UShort_t i=0; i<entries; i++)
+    {
+        //
+        // Do not use blind neighbors
+        //
+        if ((*fBadPixels)[i].IsOK())
+            continue;
+
+        //
+        // It must exist, we have created it in the loop before.
+        //
+        fEvt->GetPixById(i)->Set(nphot[i], perr[i]);
+        (*fPedPhot)[i].Set(ped[i], pedrms[i]);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  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++)
+    {
+        MCerPhotPix &pix = (*fEvt)[i];
+
+        if ((*fBadPixels)[pix.GetPixId()].IsBad())
+            pix.SetPixelUnmapped();
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Treat the blind pixels
+//
+Int_t MBadPixelsTreat::Process()
+{
+    /*
+    if (TESTBIT(fFlags, kCheckPedestalRms))
+    {
+        // if the number of blind pixels is too high, do not interpolate
+       if (CheckPedestalRms()==kFALSE)
+           return kTRUE;
+
+       if (TESTBIT(fFlags, kUseInterpolation))
+           InterpolatePedestals();
+    }
+    */
+
+    if (TESTBIT(fFlags, kUseInterpolation) && fGeomCam)
+        Interpolate();
+    else
+        Unmap();
+
+
+    //fErrors[0]++;
+
+    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 (TESTBIT(fFlags, kUseInterpolation))
+        out << "   " << GetUniqueName() << ".SetUseInterpolation();" << endl;
+    if (TESTBIT(fFlags, kUseCentralPixel))
+        out << "   " << GetUniqueName() << ".SetUseCentralPixel();" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MBadPixelsTreat.h	(revision 3781)
@@ -0,0 +1,61 @@
+#ifndef MARS_MBadPixelsTreat
+#define MARS_MBadPixelsTreat
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MBadPixelsCam;
+
+class MBadPixelsTreat : public MTask
+{
+private:
+    MGeomCam      *fGeomCam;   //!
+    MPedPhotCam   *fPedPhot;   //!
+    MCerPhotEvt   *fEvt;       //!
+    MBadPixelsCam *fBadPixels; //!
+
+    Byte_t fFlags;       // flag for the method which is used
+    Byte_t fNumMinNeighbors;
+
+
+    enum
+    {
+        kUseInterpolation = BIT(1),
+        kUseCentralPixel  = BIT(2),
+    };
+
+    static Double_t Pow2(Double_t x) { return x*x; }
+
+    void InterpolateSignal() const;
+    void InterpolatePedestals() const;
+
+    void  Interpolate() const;
+    void  Unmap() const;
+    void  StreamPrimitive(ofstream &out) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+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 SetNumMinNeighbors(UShort_t num) { fNumMinNeighbors=num; }
+
+
+    ClassDef(MBadPixelsTreat, 1) // Task to treat bad pixels (interpolation, unmapping)
+}; 
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/MMcBadPixelsSet.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbadpixels/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbadpixels/Makefile	(revision 3781)
@@ -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  = BadPixels
+
+#
+# Library name to creatre
+#
+LIB   = mbadpixels.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../manalysis -I../mgeom -I../mgui -I../mmc
+# MBadPixelsCalc  (manalysis): MPedPhotCam, MSigmabar
+# MBadPixelsCalc  (mgeom):     MGeomCam
+# MBadPixelsCam   (mgui):      MCamEvent
+# MMcBadPixelsSet (mmc):       MMcRunHeader
+
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MBadPixelsPix.cc \
+           MBadPixelsCam.cc \
+           MBadPixelsMerge.cc \
+           MBadPixelsCalc.cc \
+           MBadPixelsTreat.cc \
+           MMcBadPixelsSet.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseIncl.h	(revision 3781)
@@ -0,0 +1,12 @@
+#ifndef __CINT__
+
+/*
+#include <fstream.h>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TGListBox.h>
+*/
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/BaseLinkDef.h	(revision 3781)
@@ -0,0 +1,67 @@
+#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++ class MMath+;
+#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 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 MGGroupFrame+;
+
+// Basic containers
+#pragma link C++ class MArray;
+#pragma link C++ class MArrayB;
+#pragma link C++ class MArrayS;
+
+#pragma link C++ class MTime+;
+#pragma link C++ function operator<<(ostream&, const 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-8-4/MagicSoft/Mars/mbase/MAGIC.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MAGIC.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MAGIC.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MArgs.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArgs.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArgs.cc	(revision 3781)
@@ -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): Thomas Bretz, 7/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2003
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//
+MArgs::MArgs(int argc, char **argv) : 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);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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));
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    TIter Next(fArgv);
+    TString *s = NULL;
+    while ((s=dynamic_cast<TString*>(Next())))
+        if (*s==name)
+        {
+            delete fArgv->Remove(dynamic_cast<TObject*>(s));
+            return kTRUE;
+        }
+
+    return kFALSE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArgs.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArgs.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArgs.h	(revision 3781)
@@ -0,0 +1,60 @@
+#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);
+    ~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);
+
+    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-8-4/MagicSoft/Mars/mbase/MArray.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArray.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArray.cc	(revision 3781)
@@ -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): 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"
+
+#include <TArrayF.h>
+#include <TArrayD.h>
+
+ClassImp(MArray);
+
+// --------------------------------------------------------------------------
+//
+//  Cuts the last entries of an array containing only zeros.
+//
+void MArray::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 MArray::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;
+        }
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArray.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArray.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArray.h	(revision 3781)
@@ -0,0 +1,40 @@
+#ifndef MARS_MArray
+#define MARS_MArray
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MArray                                                                  //
+//                                                                         //
+// Abstract array base class for TObject derived Arrays                    //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+class TArrayF;
+class TArrayD;
+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;
+
+   static void  StripZeros(TArrayF &arr);
+   static void  StripZeros(TArrayD &arr);        
+   
+   ClassDef(MArray, 1)  //Abstract array base class for TObject derived Arrays
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.cc	(revision 3781)
@@ -0,0 +1,36 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// 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)             //                                                                       //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayB.h"
+
+ClassImp(MArrayB);
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayB.h	(revision 3781)
@@ -0,0 +1,174 @@
+#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];
+    }
+
+    ClassDef(MArrayB, 1)  //Array of Byte_t
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.cc	(revision 3781)
@@ -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@uni-sw.gwdg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2001
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+// 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)             //                                                                       //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MArrayS.h"
+
+ClassImp(MArrayS);
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MArrayS.h	(revision 3781)
@@ -0,0 +1,165 @@
+#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];
+    }
+
+    ClassDef(MArrayS, 1)  //Array of UShort_t
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MClone.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MClone.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MClone.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MClone.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MClone.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MClone.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MContinue.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MContinue.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MContinue.cc	(revision 3781)
@@ -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 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;
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+MContinue::MContinue(const TString rule, const char *name, const char *title)
+{
+    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)
+{
+    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)
+{
+    if (!GetFilter())
+    {
+        *fLog << err << dbginf << "Unknown fatal Error! (fFilter=NULL?!?)" << endl;
+        return kFALSE;
+    }
+
+    fTaskList = (MTaskList*)list->FindObject("MTaskList");
+    if (!fTaskList)
+    {
+        *fLog << err << dbginf << "ERROR - Tasklist '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;
+    }
+
+    GetFilter()->SetDisplay(fDisplay);
+    GetFilter()->SetLogStream(fLog);
+
+    SetBit(kFilterIsPrivate);
+
+    return GetFilter()->CallPreProcess(list);
+}
+
+void MContinue::SetDisplay(MStatusDisplay *d)
+{
+    if (GetFilter())
+        GetFilter()->SetDisplay(d);
+
+    MTask::SetDisplay(d);
+}
+
+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;
+}
+
+void MContinue::SetInverted(Bool_t i)
+{
+    GetFilter()->SetInverted(i);
+}
+
+Bool_t MContinue::IsInverted() const
+{
+    return GetFilter()->IsInverted();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MContinue.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MContinue.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MContinue.h	(revision 3781)
@@ -0,0 +1,47 @@
+#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
+
+    Int_t PreProcess(MParList *list);
+    Int_t Process() { return kCONTINUE; }
+    Int_t PostProcess();
+
+    enum { kIsOwner = BIT(14), kFilterIsPrivate = BIT(15) };
+
+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();
+
+    void SetInverted(Bool_t i=kTRUE);
+    Bool_t IsInverted() const;
+
+    void SetDisplay(MStatusDisplay *d);
+    void SetLogStream(MLog *lg);
+
+    ClassDef(MContinue, 1) //Task returning kCONTINUE
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.cc	(revision 3781)
@@ -0,0 +1,316 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 lowere recursivity
+        if (IsDir(c)==0)
+            rc += AddDirectory(c, filter, recursive-1);
+    }
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(TRegexp(f, kTRUE)).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::Check(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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 || Check(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("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;
+    }
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MDirIter.h	(revision 3781)
@@ -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  Check(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;
+
+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();
+    }
+
+    Int_t AddDirectory(const char *dir, const char *filter="", Int_t recursive=0);
+    void  Reset()
+    {
+        Close();
+        fNext.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-8-4/MagicSoft/Mars/mbase/MEvtLoop.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MEvtLoop.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MEvtLoop.cc	(revision 3781)
@@ -0,0 +1,1017 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <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
+        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 ((rc=fTaskList->Process())==kTRUE)
+        {
+            numcnts++;
+            if (!ProcessGuiEvents(++dummy))
+                break;
+        }
+    else
+        // check for number and break if unsuccessfull
+        while (dummy-- && (rc=fTaskList->Process())==kTRUE)
+        {
+            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, otherwise kFALSE.
+// 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-2002" << 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)
+{
+    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);
+
+    n += TObject::Write(name, option, bufsize);
+
+    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
+//
+// Warning: The programmer is responsible for the names to be unique in
+//          all Mars classes.
+//
+Bool_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;
+
+    prefix = fName;
+    prefix += ".";
+
+    *fLog << inf << "Reading resources for " << prefix /*TEnv::fRcName << " from " << env.GetRcName()*/ << endl;
+
+    if (fParList->ReadEnv(env, prefix, print)==kERROR)
+    {
+        *fLog << err << "ERROR - Reading Environment file." << endl;
+        return kFALSE;
+    }
+
+    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 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;
+
+    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-8-4/MagicSoft/Mars/mbase/MEvtLoop.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MEvtLoop.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MEvtLoop.h	(revision 3781)
@@ -0,0 +1,87 @@
+#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) };
+
+    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 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);
+
+    void Print(Option_t *opt="") const;
+
+    Bool_t ReadEnv(const TEnv &env, TString prefix="", Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix="", Bool_t print=kFALSE) const;
+
+    void RecursiveRemove(TObject *obj);
+
+    ClassDef(MEvtLoop, 1) // Class to execute the tasks in a tasklist
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.cc	(revision 3781)
@@ -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, 07/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+//   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"
+
+ClassImp(MFilter);
+
+MFilter::MFilter(const char *name, const char *title) : fInverted(kFALSE)
+{
+    fName  = name  ? name  : "MFilter";
+    fTitle = title ? title : "Base Class for a filter";
+}
+
+TString MFilter::GetRule() const
+{
+    return "<GetRule n/a for " + fName + ">";
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MFilter.h	(revision 3781)
@@ -0,0 +1,30 @@
+#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;
+
+    Bool_t IsConditionTrue() const { return fInverted ? !IsExpressionTrue() : IsExpressionTrue(); }
+
+    void SetInverted(Bool_t i=kTRUE) { fInverted=i; }
+    Bool_t IsInverted() const  { return fInverted; }
+
+    ClassDef(MFilter, 1)		// Abstract base class for the filters
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGGroupFrame.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGGroupFrame.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGGroupFrame.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MGGroupFrame.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGGroupFrame.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGGroupFrame.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MGList.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGList.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGList.cc	(revision 3781)
@@ -0,0 +1,270 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <TClass.h>
+#include <TGClient.h>
+#include <TGWidget.h>
+#include <TGPicture.h>
+
+ClassImp(MGList);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Before destroying the list with all its contents free all TGPicture
+//  objects in the list.
+//
+MGList::~MGList()
+{
+    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);
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  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);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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(const 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(const_cast<TGPicture*>(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)
+{
+    const TGPicture *pic = 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)
+{
+    const TGPicture *pic = 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-8-4/MagicSoft/Mars/mbase/MGList.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGList.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGList.h	(revision 3781)
@@ -0,0 +1,34 @@
+#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(const TGPicture *pic, const char *name);
+
+public:
+    MGList() : TList() {}
+    virtual ~MGList();
+
+    void Add(TObject *obj);
+    void Add(TObject *obj, Option_t *opt);
+
+    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-8-4/MagicSoft/Mars/mbase/MGMenu.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGMenu.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGMenu.cc	(revision 3781)
@@ -0,0 +1,226 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 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;
+    }
+
+    return TGMenuBar::HandleKey(event);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGMenu.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGMenu.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGMenu.h	(revision 3781)
@@ -0,0 +1,53 @@
+#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);
+
+    Bool_t HandleKey(Event_t *event);
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGTask.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGTask.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGTask.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MGTask.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGTask.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MGTask.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MInputStreamID.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MInputStreamID.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MInputStreamID.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MInputStreamID.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MInputStreamID.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MInputStreamID.h	(revision 3781)
@@ -0,0 +1,44 @@
+#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);
+
+    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-8-4/MagicSoft/Mars/mbase/MIter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MIter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MIter.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MIter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MIter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MIter.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLog.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLog.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLog.cc	(revision 3781)
@@ -0,0 +1,519 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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 "MLogPlugin.h"
+
+ClassImp(MLog);
+
+using namespace std;
+
+// 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;
+#endif
+
+    fPlugins = new TList;
+    gROOT->GetListOfCleanups()->Add(fPlugins);
+
+    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();
+
+    delete fPlugins;
+#ifdef _REENTRANT
+    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
+    Lock();
+
+    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
+    UnLock();
+}
+
+void MLog::Lock()
+{
+#ifdef _REENTRANT
+    fMuxGui->Lock();
+#endif
+}
+
+void MLog::UnLock()
+{
+#ifdef _REENTRANT
+    fMuxGui->UnLock();
+#endif
+}
+
+// --------------------------------------------------------------------------
+//
+// This is called to flush the buffer of the streaming devices
+//
+int MLog::sync()
+{
+    Lock();
+    WriteBuffer();
+    UnLock();
+
+    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)
+    {
+        Lock();
+
+        *fPPtr++ = (char)i;
+
+        if (fPPtr == fEPtr)
+            WriteBuffer();
+
+        UnLock();
+    }
+
+    return 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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";
+    fOut = fname ? new ofstream(fname) : new ofstream(/*mkstemp(*/txt/*)*/);
+    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.
+//
+void MLog::AddPlugin(MLogPlugin *plug)
+{
+    fPlugins->Add(plug);
+    plug->SetBit(kMustCleanup);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLog.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLog.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLog.h	(revision 3781)
@@ -0,0 +1,209 @@
+#ifndef MARS_MLog
+#define MARS_MLog
+
+#ifndef ROOT_TObject
+#include <TObject.h>
+#endif
+#ifndef ROOT_TString
+#include <TString.h>
+#endif
+
+#include <iostream>  // base classes for MLog
+
+#define bsz    160 // two standard lines
+
+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
+#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();
+
+    void Lock();
+    void UnLock();
+
+    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 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;
+    }
+
+    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-8-4/MagicSoft/Mars/mbase/MLogHtml.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogHtml.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogHtml.cc	(revision 3781)
@@ -0,0 +1,124 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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;
+        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()
+{
+    *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-8-4/MagicSoft/Mars/mbase/MLogHtml.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogHtml.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogHtml.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogManip.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogManip.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogManip.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogManip.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogManip.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogManip.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogPlugin.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogPlugin.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogPlugin.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogPlugin.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogPlugin.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogPlugin.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogo.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogo.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogo.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MLogo.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogo.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MLogo.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MMath.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MMath.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MMath.cc	(revision 3781)
@@ -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  3/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MMath
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MMath.h"
+
+ClassImp(MMath);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// 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
+//
+Double_t MMath::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
+{
+    const Double_t sum = s+b;
+
+    if (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-b);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MMath.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MMath.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MMath.h	(revision 3781)
@@ -0,0 +1,19 @@
+#ifndef MARS_MMath
+#define MARS_MMath
+
+#ifndef ROOT_TMath
+#include <TMath.h>
+#endif
+
+class MMath : public TMath
+{
+public:
+    static Double_t Significance(Double_t s, Double_t b);
+    static Double_t SignificanceSym(Double_t s, Double_t b);
+    static Double_t SignificanceLiMa(Double_t s, Double_t b, Double_t alpha=1);
+    static Double_t SignificanceLiMaSigned(Double_t s, Double_t b, Double_t alpha=1);
+
+    ClassDef(MMath, 0)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParContainer.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParContainer.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParContainer.cc	(revision 3781)
@@ -0,0 +1,661 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// 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, AsciiWrite
+
+#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 "MLog.h"
+#include "MLogManip.h"
+
+TList *gListOfPrimitives; // forard declaration in MParContainer.h
+
+#undef DEBUG
+//#define DEBUG
+
+ClassImp(MParContainer);
+
+using namespace std;
+
+MParContainer::MParContainer(const char *name, const char *title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+}
+
+MParContainer::MParContainer(const TString &name, const TString &title) :
+    fName(name), fTitle(title), fLog(&gLog), fDisplay(NULL), fReadyToSave(kFALSE)
+{
+}
+
+// --------------------------------------------------------------------------
+//
+//  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
+    *fLog << all << "Deleting " << GetDescriptor() << 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 char *MParContainer::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.
+    //
+    return fName==ClassName() ? ClassName() : Form("%s [%s]", fName.Data(), ClassName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  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(ifstream &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;
+}
+
+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 << warn << "No standard access for '" << part1 << "' in ";
+    *fLog << GetDescriptor() << " or one of its base classes." << endl;
+
+    TMethodCall *call = NULL;
+
+    *fLog << warn << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::Get" << part1 << "' instead <LEAKS MEMORY>" << endl;
+    call = new TMethodCall(IsA(), (TString)"Get"+part1, "");
+    if (call->GetMethod())
+        return call;
+
+    delete call;
+
+    *fLog << warn << "Trying to find MethodCall '" << ClassName();
+    *fLog << "::" << part1 << "' instead <LEAKS MEMORY>" << endl;
+    call = new TMethodCall(IsA(), part1, "");
+    if (call->GetMethod())
+        return call;
+
+    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.
+//
+Bool_t MParContainer::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (!IsEnvDefined(env, prefix, "", print))
+        return kFALSE;
+
+    *fLog << warn << "WARNING - Resource " << prefix+fName << " 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;
+}
+
+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-8-4/MagicSoft/Mars/mbase/MParContainer.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParContainer.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParContainer.h	(revision 3781)
@@ -0,0 +1,176 @@
+#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
+{
+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
+
+    // FIXME: Change to ostream!
+    virtual void StreamPrimitive(ofstream &out) 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);
+
+    virtual const char   *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; }
+
+    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(ifstream &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 Bool_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;
+
+    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-8-4/MagicSoft/Mars/mbase/MParList.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParList.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParList.cc	(revision 3781)
@@ -0,0 +1,937 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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"
+
+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;
+        }
+    }
+
+    *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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 << "' [" << cname << "] 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;
+        }
+    }
+
+    //
+    // 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.
+//
+Bool_t MParList::ReadEnv(const TEnv &env, TString prefix, Bool_t print)
+{
+    if (print)
+        *fLog << all << "MParList::ReadEnv: " << prefix << " (" << (int)print << ")" << endl;
+
+    MParContainer *cont = NULL;
+
+    MIter Next(fContainer);
+    while ((cont=Next()))
+    {
+        if (cont->InheritsFrom("MTaskList"))
+        {
+            if (cont->ReadEnv(env, prefix, print)==kERROR)
+                return kERROR;
+            continue;
+        }
+
+        // Check For: Job4.ContainerName.Varname
+        if (print)
+            *fLog << all << "Testing: " << prefix+cont->GetName() << endl;
+        Bool_t rc = cont->ReadEnv(env, prefix+cont->GetName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: Job4.MClassName.Varname
+        if (print)
+            *fLog << all << "Testing: " << prefix+cont->ClassName() << endl;
+        rc = cont->ReadEnv(env, prefix+cont->ClassName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: ContainerName.Varname
+        if (print)
+            *fLog << all << "Testing: " << cont->GetName() << endl;
+        rc = cont->ReadEnv(env, cont->GetName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: MClassName.Varname
+        if (print)
+            *fLog << all << "Testing: " << cont->ClassName() << endl;
+        rc = cont->ReadEnv(env, cont->ClassName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+    }
+
+    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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParList.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParList.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MParList.h	(revision 3781)
@@ -0,0 +1,99 @@
+#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 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;
+
+    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="");
+
+    Bool_t ReadEnv(const TEnv &env, TString prefix, Bool_t print=kFALSE);
+    Bool_t WriteEnv(TEnv &env, TString prefix, Bool_t print=kFALSE) const;
+
+    ClassDef(MParList, 1) // list of parameter containers (MParContainer)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.cc	(revision 3781)
@@ -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(kSeperator);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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(kSeperator))
+        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(kSeperator))
+        gLog << endl << setfill('-') << setw(72) << "-" << endl << endl;
+    else
+        fObject->Print(fOption);
+    return kTRUE;
+} 
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MPrint.h	(revision 3781)
@@ -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), kSeperator = 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-8-4/MagicSoft/Mars/mbase/MProgressBar.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MProgressBar.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MProgressBar.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MProgressBar.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MProgressBar.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MProgressBar.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MReadSocket.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MReadSocket.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MReadSocket.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MReadSocket.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MReadSocket.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MReadSocket.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MRunIter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MRunIter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MRunIter.cc	(revision 3781)
@@ -0,0 +1,61 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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>
+
+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 = ".";
+
+    MDirIter Next(p, Form("*_%05d_*_*.root", run), -1);
+
+    const TString name(Next());
+    if (name.IsNull())
+        return 0;
+
+    AddRunNumber(run);
+
+    return AddDirectory(gSystem->DirName(name), gSystem->BaseName(name), -1);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MRunIter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MRunIter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MRunIter.h	(revision 3781)
@@ -0,0 +1,82 @@
+#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;
+
+    void AddRunNumber(UInt_t run)
+    {
+        fRuns.Set(fRuns.GetSize()+1);
+        fRuns[fRuns.GetSize()-1] = run;
+
+        Sort();
+
+    }
+
+    void Sort()
+    {
+        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) { }
+
+    Int_t AddRun(UInt_t run, 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-8-4/MagicSoft/Mars/mbase/MSearch.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MSearch.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MSearch.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MSearch.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MSearch.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MSearch.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mbase/MStatusArray.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusArray.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusArray.cc	(revision 3781)
@@ -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 03/2004 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MStatusArray
+//
+//  Helper class for MStatusDisplay
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MStatusArray.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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusArray.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusArray.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusArray.h	(revision 3781)
@@ -0,0 +1,17 @@
+#ifndef MARS_MStatusArray
+#define MARS_MStatusArray
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class MStatusArray : public TObjArray
+{
+public:
+    TObject *DisplayIn(Option_t *o=0) const;         // *MENU*
+    TObject *Display() const { return DisplayIn(); } // *MENU*
+
+    ClassDef(MStatusArray, 0) // Helper class for status display
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusDisplay.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusDisplay.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusDisplay.cc	(revision 3781)
@@ -0,0 +1,2387 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <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 <TGStatusBar.h>          // TGStatusBar
+#include <TGFileDialog.h>         // TGFileDialog
+#include <TGProgressBar.h>        // TGHProgressBar
+#include <TRootEmbeddedCanvas.h>  // TRootEmbeddedCanvas
+
+#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 As status.&ps",   kFileSaveAsPS);
+    filemenu->AddEntry("Save As status.&gif",  kFileSaveAsGIF);
+    filemenu->AddEntry("Save As status.&C",    kFileSaveAsC);
+    filemenu->AddEntry("Save As 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 As tab-i.&ps",   kTabSaveAsPS);
+    tabmenu->AddEntry("Save As tab-i.&gif",  kTabSaveAsGIF);
+    tabmenu->AddEntry("Save As tab-i.&C",    kTabSaveAsC);
+    tabmenu->AddEntry("Save As tab-i.&root", kTabSaveAsRoot);
+    tabmenu->AddSeparator();
+    tabmenu->AddEntry("Save &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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Add the title tab
+//
+void MStatusDisplay::AddMarsTab()
+{
+    // Create Tab1
+    TGCompositeFrame *f = fTab->AddTab("-=MARS=-");
+
+    // Add MARS version
+    TGLabel *l = new TGLabel(f, Form("Official Release: V%s", MARSVER));
+    fList->Add(l);
+
+    TGLayoutHints *layb = new TGLayoutHints(kLHintsCenterX|kLHintsTop, 10, 10, 5, 5);
+    fList->Add(layb);
+    f->AddFrame(l, layb);
+
+    // Add root version
+    l = new TGLabel(f, 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);
+
+    l = new TGLabel(f, "<< Thomas Bretz >>");
+    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 = 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(Form("%s: %s", cont.GetDescriptor(), 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 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));
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+{
+    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);
+
+    // 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*)");
+
+    // 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 = 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(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);
+
+    // 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()
+{
+    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)
+            CloseWindow();
+        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;
+#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;
+
+    case kCM_COMBOBOX: // 7
+        cout << "Command-ComboBox." << 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;
+}
+
+void MStatusDisplay::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.
+
+    // 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())
+    {
+        //gLog << dbg << "delete " << fName << ";" << endl;
+        delete this;
+    }
+    fStatus = kFileExit;
+    //gLog << dbg << fName << ".fStatus=kFileExit;" << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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, const 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);
+
+    //copy primitives
+    TObject *obj;
+    TIter next(oldc.GetListOfPrimitives());
+    while ((obj=next())) {
+        gROOT->SetSelectedPad(&newc);
+        newc.GetListOfPrimitives()->Add(obj->Clone(),obj->GetDrawOption());
+    }
+    newc.Modified();
+    newc.Update();
+}
+
+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)
+{
+    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(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, 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.005, txt);
+            ps.SetTextAlign(31); // right top
+            ps.TextNDC(1, -0.005, "(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(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(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(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)
+{
+    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-8-4/MagicSoft/Mars/mbase/MStatusDisplay.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusDisplay.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MStatusDisplay.h	(revision 3781)
@@ -0,0 +1,205 @@
+#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,
+        // kPic
+        kSearch
+    } 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);
+    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, const 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;
+
+     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(Int_t num, const char *name="MStatusDisplay", Int_t option=0, Int_t bufsize=0);
+
+     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-8-4/MagicSoft/Mars/mbase/MTask.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTask.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTask.cc	(revision 3781)
@@ -0,0 +1,477 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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)
+//
+//  Version 1:
+//  ----------
+//   - first version
+//
+//  Version 2:
+//  ----------
+//   - added fSerialNumber
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTask.h"
+
+#include <fstream>
+
+#include <TBaseClass.h> // OverwritesProcess
+#include <TStopwatch.h> // TStopwatch
+
+#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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+Int_t MTask::CallPreProcess(MParList *plist)
+{
+    fStopwatch->Reset();
+
+    *fLog << all << fName << "... " << 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 << fName << "... " << 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 char *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() : Form("%s;%d", ClassName(), fSerialNumber);
+
+    return fSerialNumber>0 ?
+        Form("%s;%d [%s]", fName.Data(), fSerialNumber, ClassName()) :
+        Form("%s [%s]", fName.Data(), ClassName());
+}
+
+// --------------------------------------------------------------------------
+//
+//  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::GetNumExecutions() const
+{
+    return (UInt_t)fStopwatch->Counter();
+}
+
+// --------------------------------------------------------------------------
+//
+//  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())
+        return;
+
+    *fLog << all << setfill(' ') << setw(lvl) << " ";
+
+    if (GetCpuTime()>0 && time>0 && GetCpuTime()>=0.001*time)
+        *fLog << Form("%5.1f", GetCpuTime()/time*100) << "% ";
+    else
+        *fLog << "       ";
+    *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 (TString(cls->GetName())=="MTask")
+        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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTask.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTask.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTask.h	(revision 3781)
@@ -0,0 +1,110 @@
+#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
+
+    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) { fFilter=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 char *GetDescriptor() const;
+
+    // Task execution statistics
+    UInt_t   GetNumExecutions() 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;
+
+    // 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-8-4/MagicSoft/Mars/mbase/MTaskInteractive.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskInteractive.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskInteractive.cc	(revision 3781)
@@ -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, 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.
+//
+//  Input Containers:
+//   -/-
+//
+//  Output Containers:
+//   -/-
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MTaskInteractive.h"
+
+#include <Api.h>
+#include <TMethodCall.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MTaskInteractive);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//
+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;
+}
+
+MTaskInteractive::~MTaskInteractive()
+{
+    Free(0);
+    Free(1);
+    Free(2);
+}
+
+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;
+}
+
+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-8-4/MagicSoft/Mars/mbase/MTaskInteractive.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskInteractive.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskInteractive.h	(revision 3781)
@@ -0,0 +1,54 @@
+#ifndef MARS_MTaskInteractive
+#define MARS_MTaskInteractive
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MTaskInteractive                                                               //
+//                                                                         //
+// Does nothing than return kCONTINUE in the Process-fucntion              //
+// (use with filters)                                                      //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#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-8-4/MagicSoft/Mars/mbase/MTaskList.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskList.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskList.cc	(revision 3781)
@@ -0,0 +1,839 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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.
+//
+// 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)
+{
+    // 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)
+{
+    // 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)
+{
+    // 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);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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->OverwritesProcess())
+            fTasksProcess.Add(task);
+
+    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
+    //
+    Bool_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 << dbginf << "Fatal error occured... stopped." << endl;
+            rc = kERROR;
+            break;
+
+        case kCONTINUE:
+            //
+            // something occured: skip the rest of the tasks for this event
+            //
+            rc = kTRUE;
+            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.
+//
+Bool_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;
+        }
+
+        // Check For: Job4.ContainerName.Varname
+        if (print)
+            *fLog << all << "Testing: " << prefix+cont->GetName() << endl;
+        Bool_t rc = cont->ReadEnv(env, prefix+cont->GetName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: Job4.MClassName.Varname
+        if (print)
+            *fLog << all << "Testing: " << prefix+cont->ClassName() << endl;
+        rc = cont->ReadEnv(env, prefix+cont->ClassName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: ContainerName.Varname
+        if (print)
+            *fLog << all << "Testing: " << cont->GetName() << endl;
+        rc = cont->ReadEnv(env, cont->GetName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+
+        // Check For: MClassName.Varname
+        if (print)
+            *fLog << all << "Testing: " << cont->ClassName() << endl;
+        rc = cont->ReadEnv(env, cont->ClassName(), print);
+        if (rc==kERROR)
+            return kERROR;
+        if (rc==kTRUE)
+            continue;
+    }
+
+    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;
+
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskList.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskList.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTaskList.h	(revision 3781)
@@ -0,0 +1,86 @@
+#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 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);
+    }
+
+    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);
+
+    Bool_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-8-4/MagicSoft/Mars/mbase/MTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTime.cc	(revision 3781)
@@ -0,0 +1,525 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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!
+//
+// 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>
+
+#include <time.h>     // struct tm
+#include <sys/time.h> // struct timeval
+
+#include <TTime.h>
+
+#include "MLog.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 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");
+//
+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::Set(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);
+
+    Set(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 Set(mjd, tm, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set MTime to time expressed in a 'struct timeval'
+//
+void MTime::Set(const struct timeval &tv)
+{
+    const UInt_t mjd = 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;
+
+    Set(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 : "");
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 << 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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/MTime.h	(revision 3781)
@@ -0,0 +1,177 @@
+#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();
+
+    Bool_t   Set(UInt_t mjd, ULong_t ms, UInt_t ns=0);
+    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   UpdMagicTime(Byte_t h, Byte_t m, Byte_t s, UInt_t ns);
+    void     SetMjd(Double_t m);
+    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;
+    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; }
+
+    istream &ReadBinary(istream &fin);
+
+    operator double() const   //[s]
+    {
+        return ((Double_t)fMjd*kDay+(Long_t)fTime+fNanoSec/1e6)/1000;
+    }
+    double operator()() const //[s]
+    {
+        return operator double();
+    }
+
+    bool 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;
+    }
+    bool 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;
+    }
+
+    bool operator<=(const MTime &t) const
+    {
+        return !operator>(t);
+    }
+
+    bool operator>=(const MTime &t) const
+    {
+        return !operator<(t);
+    }
+
+    bool operator==(const MTime &t) const
+    {
+        return fNanoSec==t.fNanoSec && fTime==t.fTime && fMjd==t.fMjd;
+    }
+
+    bool operator!=(const MTime &t) const
+    {
+        return fNanoSec!=t.fNanoSec || fTime!=t.fTime || fMjd!=t.fMjd;
+    }
+
+    bool operator!() const
+    {
+        return fNanoSec==0 && (ULong_t)fTime==0 && fMjd==0;
+    }
+
+    ClassDef(MTime, 3)	//A generalized MARS time stamp
+};
+
+inline ostream &operator<<(ostream &out, const MTime &t)
+{
+    out << t.GetString();
+    return out;
+}
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mbase/Makefile	(revision 3781)
@@ -0,0 +1,86 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+INCLUDES = -I. -I../mfileio -I../mfbase -I../mastro
+# mfileio:  MRead  (MEvtLoop)
+# mfbase:   MF     (MContinue)
+# mastro:   MAstro (MTime)
+
+# @code 
+
+CINT     = Base
+LIB      = mbase.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MLogo.cc \
+           MArgs.cc \
+           MMath.cc \
+	   MLog.cc \
+           MLogManip.cc \
+           MLogPlugin.cc \
+           MLogHtml.cc \
+           MParContainer.cc \
+	   MParList.cc \
+	   MInputStreamID.cc \
+           MTask.cc \
+           MTaskInteractive.cc \
+	   MTaskList.cc \
+           MFilter.cc \
+           MEvtLoop.cc \
+           MStatusDisplay.cc \
+           MProgressBar.cc \
+           MSearch.cc \
+           MGMenu.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 \
+           MTime.cc \
+           MClone.cc \
+           MContinue.cc \
+           MPrint.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/CalibLinkDef.h	(revision 3781)
@@ -0,0 +1,38 @@
+#ifdef __CINT__
+
+#pragma link off all globals;
+#pragma link off all classes;
+#pragma link off all functions;
+
+#pragma link C++ class MCalibrate+;
+#pragma link C++ class MCalibrateData+;
+#pragma link C++ class MCalibrateRelTimes+;
+
+#pragma link C++ class MCalibrationCam+;
+#pragma link C++ class MCalibrationPix+;
+#pragma link C++ class MCalibrationRelTimeCam+;
+#pragma link C++ class MCalibrationRelTimePix+;
+#pragma link C++ class MCalibrationPedCam+;
+#pragma link C++ class MCalibrationQECam+;
+#pragma link C++ class MCalibrationQEPix+;
+#pragma link C++ class MCalibrationChargeCalc+;
+#pragma link C++ class MCalibrationChargeCam+;
+#pragma link C++ class MCalibrationChargePix+;
+#pragma link C++ class MCalibrationChargeBlindPix+;
+#pragma link C++ class MCalibrationChargePINDiode+;
+
+#pragma link C++ class MHCalibrationCam+;
+#pragma link C++ class MHCalibrationChargeCam+;
+#pragma link C++ class MHCalibrationChargePix+;
+#pragma link C++ class MHCalibrationChargeHiGainPix+;
+#pragma link C++ class MHCalibrationChargeLoGainPix+;
+#pragma link C++ class MHCalibrationChargeBlindPix+;
+#pragma link C++ class MHCalibrationChargePINDiode+;
+#pragma link C++ class MHCalibrationRelTimePix+;
+#pragma link C++ class MHCalibrationRelTimeCam+;
+
+#pragma link C++ class MMcCalibrationCalc++;
+
+#pragma link C++ class MHGausEvents++;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.cc	(revision 3781)
@@ -0,0 +1,382 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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): Markus Gaug  02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrate
+//
+//   This task takes the integrated charge from MExtractedSignal and apply
+//   the calibration constants from MCalibraitionCam to convert the summed FADC 
+//   slices to photons. The number of photons obtained is stored in MCerPhotEvt. 
+//
+//   Selection of different calibration methods is possible through the 
+//   SetCalibrationMode member function
+//
+//   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 
+//   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!   
+//
+//   Input Containers:
+//    MExtractedSingal
+//    MCalibrationChargeCam
+//
+//   Output Containers:
+//    MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrate.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MH.h"
+
+#include "MGeomCam.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCerPhotEvt.h"
+
+ClassImp(MCalibrate);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrate::MCalibrate(CalibrationMode_t calmode,const char *name, const char *title) 
+    : fGeomCam(NULL), fCalibrations(NULL), fQEs(NULL), fBadPixels(NULL), fSignals(NULL), 
+      fCerPhotEvt(NULL), fCalibrationMode(calmode)
+{
+    fName  = name  ? name  : "MCalibrate";
+    fTitle = title ? title : "Task to calculate the number of photons in one event";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MGeomCam
+//  - MCalibrationChargeCam
+//  - MExtractedSignalCam
+//  - MBadPixelsCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MCerPhotEvt
+//
+Int_t MCalibrate::PreProcess(MParList *pList)
+{
+
+    fSignals = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+
+    if (!fSignals)
+    {
+      *fLog << err << AddSerialNumber("MExtractedSignalCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+    if (!fBadPixels)
+      *fLog << warn << AddSerialNumber("MBadPixelsCam") << " not found ... no action" << endl;
+    
+    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;
+	  }
+        
+      }
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+        return kFALSE;
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for validity of the selected calibration method, switch to a 
+// different one in case of need
+//
+Bool_t MCalibrate::ReInit(MParList *pList)
+{
+
+  if(fCalibrationMode == kBlindPixel && !fQEs->IsBlindPixelMethodValid())
+    {
+      *fLog << warn << GetDescriptor() 
+            << "Warning: Blind pixel calibration method not valid, switching to F-factor method" << endl;
+      fCalibrationMode = kFfactor;
+    }
+  
+  if(fCalibrationMode == kPinDiode && !fQEs->IsPINDiodeMethodValid())
+    { 
+      *fLog << warn << GetDescriptor() 
+            << "Warning: PIN diode calibration method not valid, switching to F-factor method" << endl;
+      fCalibrationMode = kFfactor;
+    }
+
+  if(fCalibrationMode == kCombined && !fQEs->IsCombinedMethodValid())
+    { 
+      *fLog << warn << GetDescriptor() 
+            << "Warning: Combined calibration method not valid, switching to F-factor method" << endl;
+      fCalibrationMode = kFfactor;
+    }
+
+  switch(fCalibrationMode)
+    {
+    case kBlindPixel:
+      break;
+    case kFfactor:
+      break;
+    case kPinDiode:
+      *fLog << err << GetDescriptor() 
+                    << ": PIN Diode Calibration mode not yet available " << endl;
+      return kFALSE;
+      break;
+    case kCombined:
+      *fLog << err << GetDescriptor() 
+                    << ": Combined Calibration mode not yet available " << endl;
+      return kFALSE;
+      break;
+    case kDummy:
+      *fLog << warn << GetDescriptor() 
+                    << ": WARNING: Dummy calibration, no calibration applied!!" << endl;
+      break;
+    case kNone:
+      *fLog << warn << GetDescriptor() 
+                    << ": WARNING: No calibration applied!!" << endl;
+      break;
+    default:
+      *fLog << warn << GetDescriptor() 
+            << ": WARNING: Calibration mode value ("
+            <<fCalibrationMode<<") not known" << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrate::Process()
+{
+
+  //
+  // For the moment, we use only a dummy zenith for the calibration:
+  //
+  const Float_t zenith = 0;
+
+  /*
+    if (fCalibrations->GetNumPixels() != (UInt_t)fSignals->GetSize())
+    {
+        // FIXME: MExtractedSignal must be of variable size -
+        //        like MCerPhotEvt - because we must be able
+        //        to reduce size by zero supression
+        //        For the moment this check could be done in ReInit...
+        *fLog << err << "MExtractedSignal and MCalibrationCam have different sizes... abort." << endl;
+        return kFALSE;
+    }
+  */
+
+  UInt_t npix = fSignals->GetSize();
+
+  Float_t hiloconv      = 0.;
+  Float_t hiloconverr   = 0.;
+  Float_t calibConv     = 0.;
+  Float_t calibConvVar  = 0.;
+  Float_t calibFFactor  = 0.;
+  Float_t calibQE       = 1.;
+  Float_t calibQEVar    = 0.;
+  
+  for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+
+      if(fCalibrationMode!=kNone)
+	{
+
+	  
+	  MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCalibrations)[pixidx];
+	  MCalibrationQEPix     &qe  = (MCalibrationQEPix&)    (*fQEs         )[pixidx];
+
+          if (fBadPixels)
+            {
+              MBadPixelsPix         &bad = (*fBadPixels)[pixidx];
+              if (!bad.IsCalibrationResultOK())
+                continue;
+            }
+            
+          calibConv      = pix.GetMeanConvFADC2Phe();
+          calibConvVar   = pix.GetMeanConvFADC2PheVar();
+          calibFFactor   = pix.GetMeanFFactorFADC2Phot();
+
+	  switch(fCalibrationMode)
+	    {
+	    case kBlindPixel:
+              if (qe.IsBlindPixelMethodValid())
+		{
+                  calibQE      = qe.GetQECascadesBlindPixel   ( zenith );
+                  calibQEVar   = qe.GetQECascadesBlindPixelVar( zenith );
+		}
+              else
+                continue;
+	      break;
+	    case kPinDiode:
+              if (qe.IsPINDiodeMethodValid())
+		{
+                  calibQE      = qe.GetQECascadesPINDiode   ( zenith );
+                  calibQEVar   = qe.GetQECascadesPINDiodeVar( zenith );
+		}
+		else
+                  continue;
+	      break;
+	    case kFfactor:
+              if (pix.IsFFactorMethodValid())
+		{
+                  calibQE      = qe.GetQECascadesFFactor   ( zenith );
+                  calibQEVar   = qe.GetQECascadesFFactorVar( zenith );
+		}
+              else
+                continue;
+	      break;
+	    case kCombined:
+              if (qe.IsCombinedMethodValid())
+		{
+                  calibQE      = qe.GetQECascadesCombined   ( zenith );
+                  calibQEVar   = qe.GetQECascadesCombinedVar( zenith );
+		}
+              else
+                continue;
+              break;
+            case kDummy:
+ 	      hiloconv     = 1.;
+	      hiloconverr  = 0.;
+	      calibQE      = 1.;
+	      calibQEVar   = 0.;
+              break;
+
+	    } /* switch calibration mode */
+	  
+	  hiloconv   = pix.GetConversionHiLo   ();
+	  hiloconverr= pix.GetConversionHiLoErr();
+	  
+	} /* if(fCalibrationMode!=kNone) */
+      else
+      {
+	  hiloconv       = 1.;
+	  hiloconverr    = 0.;
+	  calibConv      = 1.;
+	  calibConvVar   = 0.;
+	  calibFFactor   = 0.;
+	  calibQE        = 1.;
+	  calibQEVar     = 0.;
+      }      
+      MExtractedSignalPix &sig =  (*fSignals)[pixidx];
+      
+      Float_t signal;
+      Float_t signalErr = 0.;
+      Float_t nphot,nphotErr;
+            
+      if (sig.IsLoGainUsed())
+        {
+          signal    = sig.GetExtractedSignalLoGain()*hiloconv;
+          signalErr = signal*hiloconverr;
+        }
+      else
+        {
+	  if (sig.GetExtractedSignalHiGain() > 9999.)
+	    {
+	      signal    = 0.;
+	      signalErr = 0.;
+	    }
+	  else
+	    signal = sig.GetExtractedSignalHiGain();
+        }
+      
+      nphot    = signal*calibConv/calibQE;
+      nphotErr = calibFFactor*TMath::Sqrt(nphot);
+
+      //
+      // The following part is the outcommented first version of the error calculation
+      // Contact Markus Gaug for questions (or wait for the next documentation update...)
+      //
+      /*
+        nphotErr = signal    > 0 ? signalErr*signalErr / (signal * signal)  : 0.
+                 + calibConv > 0 ? calibConvVar  / (calibConv * calibConv ) : 0.
+                 + calibQE   > 0 ? calibQEVar    / (calibQE   * calibQE   ) : 0.;
+        nphotErr  = TMath::Sqrt(nphotErr) * nphot;
+      */
+
+      MCerPhotPix *cpix = fCerPhotEvt->AddPixel(pixidx, nphot, nphotErr);
+
+      if (sig.GetNumLoGainSaturated() > 0)
+	cpix->SetPixelSaturated();
+
+      if (sig.GetNumHiGainSaturated() > 0)
+	cpix->SetPixelHGSaturated();
+
+
+    } /* for (UInt_t pixidx=0; pixidx<npix; pixidx++) */
+  
+  fCerPhotEvt->FixSize();
+  fCerPhotEvt->SetReadyToSave();
+  
+  return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrate.h	(revision 3781)
@@ -0,0 +1,54 @@
+#ifndef MARS_MCalibrate
+#define MARS_MCalibrate
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrate                                                              //
+//                                                                         //
+// Integrates the desired ADC time slices of one pixel and apply           //
+// calibration constants                                                   //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractedSignalCam;
+class MCerPhotEvt;
+
+class MCalibrate : public MTask
+{
+private:
+    MGeomCam              *fGeomCam;      // Camera geometry container
+    MCalibrationChargeCam *fCalibrations; // Calibration constants
+    MCalibrationQECam     *fQEs;          // Quantum efficiencies
+    MBadPixelsCam         *fBadPixels;    // Bad Pixels information
+    MExtractedSignalCam   *fSignals;      // Integrated charge in FADCs counts
+    MCerPhotEvt           *fCerPhotEvt;   // Cerenkov Photon Event used for calculation
+
+    Float_t fConversionHiLo;
+    UShort_t fCalibrationMode;
+    
+    Int_t PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t Process();
+
+public:
+
+    enum CalibrationMode_t{kNone=0,kBlindPixel,kFfactor,kPinDiode,kCombined, kDummy};
+    static const CalibrationMode_t kDefault = kBlindPixel;
+
+    MCalibrate(CalibrationMode_t calmode = kDefault,const char *name=NULL, const char *title=NULL);
+
+    void SetConversionHiLo(Float_t conv) { fConversionHiLo = conv; };
+    void SetCalibrationMode(CalibrationMode_t calmode=kDefault){ fCalibrationMode=calmode;};
+    
+    ClassDef(MCalibrate, 0)   // Task to calculate cerenkov photons using calibration constants
+};
+ 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.cc	(revision 3781)
@@ -0,0 +1,379 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MCalibrateData
+//
+//   This task takes the integrated charge from MExtractedSignal and apply
+//   the calibration constants from MCalibraitionCam to the charge. Then
+//   stores number of photons obtained in MCerPhotEvt. Selection of different
+//   calibration methods is allowed through SetCalibrationMode member function
+//
+//   in ReInit the MPedPhotCam container is filled using the information from
+//   MPedestalCam, MExtractedSignalCam and MCalibrationCam
+//
+//   Input Containers:
+//    MPedestalCam
+//    MExtractedSingalCam
+//    MCalibrationChargeCam
+//    MCalibrationQECam
+//
+//   Output Containers:
+//    MPedPhotCam
+//    MCerPhotEvt
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MCalibrateData.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 "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCerPhotEvt.h"
+
+ClassImp(MCalibrateData);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MCalibrateData::MCalibrateData(CalibrationMode_t calmode,const char *name, const char *title) 
+    : fCam(NULL), fPedestal(NULL), fBadPixels(NULL), fCalibrations(NULL), fSignals(NULL), 
+      fPedPhot(NULL), fCerPhotEvt(NULL), fCalibrationMode(calmode)
+{
+    fName  = name  ? name  : "MCalibrateData";
+    fTitle = title ? title : "Task to calculate the number of photons in one event";
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MGeomCam
+//  - MPedestalCam
+//  - MCalibrationChargeCam
+//  - MCalibrationQECam
+//  - MExtractedSignalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MPedPhotCam
+//  - MCerPhotEvt
+//
+Int_t MCalibrateData::PreProcess(MParList *pList)
+{
+    fPedestal = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+    if (!fPedestal)
+    {
+      *fLog << err << AddSerialNumber("MPedestalCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+
+    fSignals = (MExtractedSignalCam*)pList->FindObject(AddSerialNumber("MExtractedSignalCam"));
+    if (!fSignals)
+    {
+      *fLog << err << AddSerialNumber("MExtractedSignalCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    fBadPixels = (MBadPixelsCam*)pList->FindObject(AddSerialNumber("MBadPixelsCam"));
+
+    if (!fBadPixels)
+    {
+      *fLog << err << AddSerialNumber("MBadPixelsCam") << " not found ... aborting" << endl;
+        return kFALSE;
+    }
+
+    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;
+        }
+    }
+
+    fPedPhot = (MPedPhotCam*)pList->FindCreateObj(AddSerialNumber("MPedPhotCam"));
+    if (!fPedPhot)
+        return kFALSE;
+
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindCreateObj(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+        return kFALSE;
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+
+  if(fCalibrationMode == kBlindPixel && !fQEs->IsBlindPixelMethodValid())
+    {
+      *fLog << warn << GetDescriptor() << "Warning: Blind pixel calibration method not valid, switching to F-factor method" << endl;
+      fCalibrationMode = kFfactor;
+    }
+
+  if(fCalibrationMode == kPinDiode && !fQEs->IsPINDiodeMethodValid())
+    { 
+      *fLog << warn << GetDescriptor() << "Warning: PIN diode calibration method not valid, switching to F-factor method" << endl;
+      fCalibrationMode = kFfactor;
+    }
+
+  //---------------------------------------------
+  // fill MPedPhot container using the informations from
+  // MPedestalCam, MExtractedSignalCam and MCalibrationCam
+
+  fNumUsedHiGainFADCSlices = fSignals->GetNumUsedHiGainFADCSlices();
+
+  // is pixid equal to pixidx ?
+  if (    (Int_t)(fPedestal->GetSize()) != fSignals->GetSize())
+  {
+    *fLog << err << "MCalibrateData::ReInit(); sizes of MPedestalCam and MCalibrationCam are different" 
+          << endl;
+  } 
+
+  *fLog << all << "MCalibrateData::ReInit(); fill MPedPhotCam container"
+        << endl;
+  *fLog << all << "     fNumUsedHiGainADCSlices = " 
+        <<  fNumUsedHiGainFADCSlices << endl;
+  *fLog << all << "     pixid, calibrationConversionFactor, ped, pedRMS, pedphot, pedphotRMS :"
+        << endl;
+  for (Int_t pixid=0; pixid<fPedestal->GetSize(); pixid++)
+  {
+    const MPedestalPix    &ped = (*fPedestal)[pixid];
+
+    // pedestals/(used FADC slices)   in [ADC] counts
+    Float_t pedes  = ped.GetPedestal()    * fNumUsedHiGainFADCSlices;
+    Float_t pedrms = ped.GetPedestalRms() * sqrt(fNumUsedHiGainFADCSlices);
+
+    //----------------------------------
+    // get phe/ADC conversion factor
+
+    Float_t hiloconv;
+    Float_t hiloconverr;
+    Float_t calibConv;
+    Float_t calibFFactor;
+
+    if ( !GetConversionFactor(pixid, hiloconv, hiloconverr,
+			      calibConv, calibFFactor ))
+      continue;
+
+    //---------------------------------- 
+
+    // pedestals/(used FADC slices)   in [number of photons] 
+    Float_t pedphot    = pedes  * calibConv;
+    Float_t pedphotrms = pedrms * calibConv;
+
+    (*fPedPhot)[pixid].Set(pedphot, pedphotrms);
+
+    *fLog << all << pixid << ",  " << calibConv << ",  "
+          << ped.GetPedestal() << ",  " << ped.GetPedestalRms() << ",  " 
+          << pedphot << ",  " << pedphotrms << endl;
+  }
+
+  //---------------------------------------------
+
+  fPedPhot->SetReadyToSave();
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get conversion factor and its error from MCalibrationCam
+// 
+//
+Bool_t MCalibrateData::GetConversionFactor(UInt_t pixidx,
+ Float_t &hiloconv, Float_t &hiloconverr,
+ Float_t &calibConv, Float_t &calibFFactor)
+{
+
+  //
+  // For the moment, we use only a dummy zenith for the calibration:
+  //
+  const Float_t zenith = -1.;
+
+  hiloconv     = 1.;
+  hiloconverr  = 0.;
+  calibConv    = 1.;
+  calibFFactor = 0.;
+
+  if(fCalibrationMode!=kNone)
+  {
+    MCalibrationChargePix &pix   = (MCalibrationChargePix&)(*fCalibrations)[pixidx];       
+    MCalibrationQEPix     &qepix = (MCalibrationQEPix&)    (*fQEs)         [pixidx];       
+    MBadPixelsPix         &bad   = (*fBadPixels)[pixidx];
+    
+    if (!bad.IsCalibrationResultOK())
+      return kFALSE;
+    
+    hiloconv   = pix.GetConversionHiLo();
+    hiloconverr= pix.GetConversionHiLoErr();
+
+    const Float_t pheConv = pix.GetMeanConvFADC2Phe();
+    calibFFactor          = pix.GetMeanFFactorFADC2Phot();
+    Float_t calibQE       = 1.;
+    
+    switch(fCalibrationMode)
+    {
+      case kBlindPixel:
+        calibQE      = qepix.GetQECascadesBlindPixel   ( zenith );
+        //        calibQEVar   = qepix.GetQECascadesBlindPixelVar( zenith );
+      break;
+      case kFfactor:
+        calibQE      = qepix.GetQECascadesFFactor   ( zenith );
+        //        calibQEVar   = qepix.GetQECascadesFFactorVar( zenith );
+      break;
+      default:
+      *fLog << warn << "MCalibrateData::GetConversionFactor; Warning: Calibration mode value ("<<fCalibrationMode<<") not known" << endl;
+	      break;
+    }
+    calibConv = pheConv / calibQE;
+
+  }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Apply the calibration factors to the extracted signal according to the 
+// selected calibration method
+//
+Int_t MCalibrateData::Process()
+{
+  /*
+    if (fCalibrations->GetNumPixels() != (UInt_t)fSignals->GetSize())
+    {
+        // FIXME: MExtractedSignal must be of variable size -
+        //        like MCerPhotEvt - because we must be able
+        //        to reduce size by zero supression
+        //        For the moment this check could be done in ReInit...
+        *fLog << err << "MExtractedSignal and MCalibrationCam have different sizes... abort." << endl;
+        return kFALSE;
+    }
+  */
+
+  UInt_t npix = fSignals->GetSize();
+
+  Float_t hiloconv;
+  Float_t hiloconverr;
+  Float_t calibrationConversionFactor;
+  Float_t calibrationConversionFactorErr;
+  
+  for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+      if ( !GetConversionFactor(pixidx, hiloconv, hiloconverr,
+	    calibrationConversionFactor, calibrationConversionFactorErr) )
+        continue;
+      
+      MExtractedSignalPix &sig =  (*fSignals)[pixidx];
+      
+      Float_t signal;
+      Float_t signalErr = 0.;
+      Float_t nphot,nphotErr;
+            
+      if (sig.IsLoGainUsed())
+        {
+          signal    = sig.GetExtractedSignalLoGain()*hiloconv;
+          signalErr = signal*hiloconverr;
+        }
+      else
+        {
+	  if (sig.GetExtractedSignalHiGain() > 9999.)
+	    {
+	      signal = 0.;
+	      signalErr = 0.;
+	    }
+	  else
+	    signal = sig.GetExtractedSignalHiGain();
+        }
+      
+      nphot    = signal*calibrationConversionFactor;
+      nphotErr = signal*calibrationConversionFactorErr
+	*signal*calibrationConversionFactorErr
+	+signalErr*calibrationConversionFactor
+	*signalErr*calibrationConversionFactor;
+      
+      nphotErr  = TMath::Sqrt(nphotErr);
+      
+      MCerPhotPix *cpix = fCerPhotEvt->AddPixel(pixidx, nphot, nphotErr);
+
+      if (sig.GetNumHiGainSaturated() > 0)
+	cpix->SetPixelHGSaturated();
+
+      if (sig.GetNumLoGainSaturated() > 0)
+	cpix->SetPixelSaturated();
+    }
+  
+  fCerPhotEvt->FixSize();
+  fCerPhotEvt->SetReadyToSave();
+  
+  return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateData.h	(revision 3781)
@@ -0,0 +1,83 @@
+#ifndef MARS_MCalibrateData
+#define MARS_MCalibrateData
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MCalibrateData
+//                                                                         //
+// Integrates the desired ADC time slices of one pixel and apply           //
+// calibration constants                                                   //
+//                                                                         //
+// Differences between MCalibrateData and MCalibrate :
+// in MCalibrateData
+// - in ReInit the MPedPhot container is filled using
+//      - the pedstals/slice from MPedestalCam
+//      - the number of used FADC slices from MExtractedSignalCam   
+//      - the photon/ADC conversion factor from MCalibrationCam
+//                                                                         //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MGeomCam;
+class MBadPixelsCam;
+class MPedestalCam;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MExtractedSignalCam;
+
+class MPedPhotCam;
+class MCerPhotEvt;
+
+class MCalibrateData : public MTask
+{
+private:
+    MGeomCam              *fCam;
+    MPedestalCam          *fPedestal;     // Pedestals/slice [ADC counts]
+    MBadPixelsCam         *fBadPixels;    // Bad Pixels information
+    MCalibrationChargeCam *fCalibrations; // Calibration constants
+    MCalibrationQECam     *fQEs;          // Quantum efficiencies
+    MExtractedSignalCam   *fSignals;      // Integrated charge in FADCs counts
+
+    MPedPhotCam           *fPedPhot;      // Pedestals/(used slices) [photons]
+    MCerPhotEvt           *fCerPhotEvt;   // Cerenkov Photon Event used for calculation
+
+    Float_t fNumUsedHiGainFADCSlices;
+    Float_t fNumUsedLoGainFADCSlices;
+
+    Float_t  fConversionHiLo;
+    UShort_t fCalibrationMode;
+
+    Bool_t GetConversionFactor(UInt_t, 
+                               Float_t &, Float_t &, Float_t &, Float_t &);    
+
+    Int_t  PreProcess(MParList *pList);
+    Bool_t ReInit(MParList *pList);
+    Int_t  Process();
+
+public:
+
+    enum CalibrationMode_t{kNone=0,kBlindPixel,kFfactor,kPinDiode,kCombined};
+    static const CalibrationMode_t kDefault = kBlindPixel;
+
+    MCalibrateData(CalibrationMode_t calmode = kDefault,const char *name=NULL, const char *title=NULL);
+
+    void SetConversionHiLo(Float_t conv) { fConversionHiLo = conv; };
+    void SetCalibrationMode(CalibrationMode_t calmode=kDefault){ fCalibrationMode=calmode;};
+    
+    ClassDef(MCalibrateData, 0)   // Task to calculate cerenkov photons using calibration constants
+};
+ 
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.cc	(revision 3781)
@@ -0,0 +1,202 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 MCerPhotEvt. 
+//
+//   Input Containers:
+//    MArrivalTimeCam 
+//    MCalibrationRelTimeCam
+//
+//   Output Containers:
+//    MArrivalTime
+//
+//////////////////////////////////////////////////////////////////////////////
+#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 "MArrivalTime.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 = (MArrivalTime*)pList->FindCreateObj(AddSerialNumber("MArrivalTime"));
+    if (!fArrivalTime)
+      {
+        *fLog << err << AddSerialNumber("MArrivalTime") << ": Cannot create ... aborting." << endl;
+        return kFALSE;
+      }
+    
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for validity of the selected calibration method, switch to a 
+// different one in case of need
+//
+Bool_t MCalibrateRelTimes::ReInit(MParList *pList)
+{
+  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 MCerPhotEvt - 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;
+    }
+  */
+
+  UInt_t npix = fSignals->GetSize();
+
+  Float_t offset    = 0.;
+  Float_t precision = 0.;
+  
+  for (UInt_t pixidx=0; pixidx<npix; pixidx++)
+    {
+
+      MCalibrationRelTimePix &pix = (MCalibrationRelTimePix&)(*fCalibrations)[pixidx];
+      
+      if (fBadPixels)
+        {
+          MBadPixelsPix          &bad = (*fBadPixels)[pixidx];
+          if (!bad.IsCalibrationResultOK())
+            continue;
+        }
+      
+      offset     = pix.GetTimeOffset();
+      precision  = pix.GetTimePrecision();
+      
+      MArrivalTimePix &sig =  (*fSignals)[pixidx];
+      
+      Float_t signal;
+      Float_t sigerr;
+            
+      if (sig.IsLoGainUsed())
+        {
+          signal = sig.GetArrivalTimeLoGain();
+          sigerr = sig.GetArrivalTimeLoGainError();
+        }
+      else
+        {
+          signal = sig.GetArrivalTimeHiGain();
+          sigerr = sig.GetArrivalTimeHiGainError();
+        }
+      
+      const Float_t time = signal - offset;
+      Float_t err        = sigerr*sigerr + precision*precision;
+      if (err > 0)
+        err = TMath::Sqrt(err);
+
+      fArrivalTime->SetTime(pixidx,time);
+      fArrivalTime->SetTimeErr(pixidx,err);
+
+    } /* for (UInt_t pixidx=0; pixidx<npix; pixidx++) */
+  
+  fArrivalTime->SetReadyToSave();
+  
+  return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrateRelTimes.h	(revision 3781)
@@ -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 MArrivalTime;
+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
+    MArrivalTime           *fArrivalTime;  // Calibrated arrival times
+
+    Int_t PreProcess(MParList *pList);
+    Bool_t ReInit(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-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.cc	(revision 3781)
@@ -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): Markus Gaug   11/2003 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                               
+// MCalibrationCam                                               
+//                                                               
+// Base class for Camera Calibration results. 
+//
+// Contains TClonesArrays 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 TClonesArrays have to enlarged by the corresponding calls to (e.g. in MGeomApply): 
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors() 
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationCam.h"
+
+#include <TClonesArray.h>
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationPix.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 TClonesArray of MBadPixelsPix containers for the TClonesArray'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)
+    : fNumHiGainFADCSlices(0.), fNumLoGainFADCSlices(0.), fPulserColor(kNONE), 
+      fPixels(NULL), fAverageAreas(NULL), fAverageSectors(NULL)
+{
+    fName  = name  ? name  : "MCalibrationCam";
+    fTitle = title ? title : "Base class Storage container for Camera Calibration";
+
+    fAverageBadAreas    = new TClonesArray("MBadPixelsPix",1);
+    fAverageBadSectors  = new TClonesArray("MBadPixelsPix",1);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the following TClonesArray's of MCalibrationPix containers (if exist):
+// - fPixels
+// - fAverageAreas
+// - fAverageSectors
+//  
+// Deletes the following TClonesArray'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;
+
+  delete fAverageBadAreas;
+  delete fAverageBadSectors;
+  
+}
+
+// --------------------------------------
+//
+// Calls the ForEach macro for the TClonesArray 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)();
+
+  //
+  // another ForEach does not compile, thus have to do the loop ourselves:
+  //
+  for (Int_t i=0;i<GetAverageAreas();i++)
+    {
+      fAverageAreas[i].Clear();
+      fAverageBadAreas[i].Clear();
+    }
+
+  //
+  // another ForEach does not compile, thus have to do the loop ourselves:
+  //
+  for (Int_t i=0;i<GetAverageSectors();i++)
+    {
+      fAverageSectors[i].Clear();
+      fAverageBadSectors[i].Clear();
+    }
+  
+  return;
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for fPixels
+//
+void MCalibrationCam::InitSize(const UInt_t i)
+{
+  fPixels->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageAreas
+// - fAverageBadAreas
+//
+void MCalibrationCam::InitAverageAreas(const UInt_t i)
+{
+  fAverageAreas->ExpandCreate(i);
+  fAverageBadAreas->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls TClonesArray::ExpandCreate() for:
+// - fAverageSectors
+// - fAverageBadSectors
+//
+void MCalibrationCam::InitAverageSectors(const UInt_t i)
+{
+  fAverageSectors->ExpandCreate(i);
+  fAverageBadSectors->ExpandCreate(i);
+}
+
+// -------------------------------------------------------------------
+//
+// Calls:
+// - InitSize()
+// - InitAverageAreas()
+// - InitAverageSectors()
+//
+void MCalibrationCam::Init(const MGeomCam &geom)
+{
+  InitSize          (geom.GetNumPixels() );
+  InitAverageAreas  (geom.GetNumAreas()  );
+  InitAverageSectors(geom.GetNumSectors());
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fPixels 
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetSize() const
+{
+  return fPixels->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageAreas
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetAverageAreas() const
+{
+  return fAverageAreas->GetEntriesFast();
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TClonesArray fAverageSectors
+// independently if the MCalibrationPix is filled with values or not.
+//
+const Int_t MCalibrationCam::GetAverageSectors() const
+{
+  return fAverageSectors->GetEntriesFast();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+MCalibrationPix &MCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fPixels->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th pixel (pixel number)
+//
+const MCalibrationPix &MCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MCalibrationPix*>(fPixels->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageArea(UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageArea(UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MCalibrationPix &MCalibrationCam::GetAverageSector(UInt_t i)
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MCalibrationPix &MCalibrationCam::GetAverageSector(UInt_t i) const 
+{
+  return *static_cast<MCalibrationPix*>(fAverageSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadArea(UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (area number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadArea(UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+MBadPixelsPix &MCalibrationCam::GetAverageBadSector(UInt_t i)
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th average pixel (sector number)
+//
+const MBadPixelsPix &MCalibrationCam::GetAverageBadSector(UInt_t i) const 
+{
+  return *static_cast<MBadPixelsPix*>(fAverageBadSectors->UncheckedAt(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();
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationCam.h	(revision 3781)
@@ -0,0 +1,81 @@
+#ifndef MARS_MCalibrationCam
+#define MARS_MCalibrationCam
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+class TClonesArray;
+
+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:
+
+  Float_t fNumHiGainFADCSlices;      // Number High-Gain FADC slices used by extractor      
+  Float_t fNumLoGainFADCSlices;      // Number Low -Gain FADC slices used by extractor
+  
+  PulserColor_t fPulserColor;        // Colour of the pulsed LEDs
+
+  TClonesArray *fPixels;             //-> Array of MCalibrationPix, one per pixel
+  TClonesArray *fAverageAreas;       //-> Array of MCalibrationPix, one per pixel area
+  TClonesArray *fAverageSectors;     //-> Array of MCalibrationPix, one per camera sector
+  TClonesArray *fAverageBadAreas;    //-> Array of MBadPixelsPix,   one per pixel area
+  TClonesArray *fAverageBadSectors;  //-> Array of MBadPixelsPix,   one per camera sector
+  
+public:
+
+  MCalibrationCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationCam();
+  
+  virtual void Clear           ( Option_t *o="");
+  virtual void DrawPixelContent( Int_t num) const;    
+
+  // Getters
+  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;
+        MBadPixelsPix   &GetAverageBadSector ( UInt_t i );
+  const MBadPixelsPix   &GetAverageBadSector ( UInt_t i ) const;
+        MCalibrationPix &GetAverageSector    ( UInt_t i );
+  const Int_t            GetAverageSectors   ()           const;  
+  const MCalibrationPix &GetAverageSector    ( UInt_t i ) const;
+  const Float_t          GetNumHiGainFADCSlices()         const { return fNumHiGainFADCSlices; }
+  const Float_t          GetNumLoGainFADCSlices()         const { return fNumLoGainFADCSlices; }  
+  virtual 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               );
+  void  InitAverageAreas       ( const UInt_t i               );
+  void  InitAverageSectors     ( const UInt_t i               );
+
+  // Setters
+  void  SetNumHiGainFADCSlices ( const Float_t f              )  { fNumHiGainFADCSlices = f; }
+  void  SetNumLoGainFADCSlices ( const Float_t f              )  { fNumLoGainFADCSlices = f; }  
+  void  SetPulserColor         ( const PulserColor_t col=kCT1 )  { fPulserColor = col; }
+  
+  ClassDef(MCalibrationCam, 1)	// Base class Container for Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.cc	(revision 3781)
@@ -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): Markus Gaug   02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                               
+// MCalibrationChargeBlindPix    
+//
+// 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:
+// - gkBlindPixelArea: 100 mm^2
+// - Average QE of Blind Pixel: 
+//    gkBlindPixelQEGreen: 0.154
+//    gkBlindPixelQEBlue : 0.226
+//    gkBlindPixelQEUV   : 0.247
+//    gkBlindPixelQECT1  : 0.247
+// - Average QE Error of Blind Pixel: 
+//    gkBlindPixelQEGreenErr: 0.015;
+//    gkBlindPixelQEBlueErr : 0.02;
+//    gkBlindPixelQEUVErr   : 0.02;
+//    gkBlindPixelQECT1Err  : 0.02;
+// - Attenuation factor Blind Pixel:
+//    gkBlindPixelAttGreen :  1.97;
+//    gkBlindPixelAttBlue  :  1.96;
+//    gkBlindPixelAttUV    :  1.95;
+//    gkBlindPixelAttCT1   :  1.95;
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeBlindPix.h"
+#include "MCalibrationCam.h"
+
+#include <TH1.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MCalibrationChargeBlindPix);
+
+using namespace std;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelArea       = 100;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelAttGreen   = 1.97;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelAttBlue    = 1.96;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelAttUV      = 1.95;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelAttCT1     = 1.95;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEGreen    = 0.154;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEBlue     = 0.226;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEUV       = 0.247;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQECT1      = 0.247;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEGreenErr = 0.015;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEBlueErr  = 0.02;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQEUVErr    = 0.02;
+const Float_t MCalibrationChargeBlindPix::gkBlindPixelQECT1Err   = 0.02;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Calls:
+// - Clear()
+//
+MCalibrationChargeBlindPix::MCalibrationChargeBlindPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MCalibrationChargeBlindPix";
+  fTitle = title ? title : "Container of the fit results of the blind pixel";
+
+  Clear();
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Sets:
+// - all flags to kFALSE
+// - all variables to -1.
+// - the fColor to MCalibrationCam::kNONE
+//
+// Calls: 
+// - MCalibrationChargePix::Clear()
+//
+void MCalibrationChargeBlindPix::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);
+
+  MCalibrationChargePix::Clear();
+}
+
+void  MCalibrationChargeBlindPix::SetFluxInsidePlexiglassAvailable( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kFluxInsidePlexiglassAvailable) : CLRBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Oscillating Bit from outside 
+//
+void  MCalibrationChargeBlindPix::SetOscillating( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kOscillating) : CLRBIT(fFlags,kOscillating);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the ChargeFitValid Bit from outside 
+//
+void  MCalibrationChargeBlindPix::SetChargeFitValid( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kChargeFitValid) : CLRBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the PedestalFitValid Bit from outside 
+//
+void  MCalibrationChargeBlindPix::SetPedestalFitOK( const Bool_t b)
+{
+    b ? SETBIT(fFlags,kPedestalFitOK) : CLRBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the SinglePheFitValid Bit from outside 
+//
+void  MCalibrationChargeBlindPix::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
+// 
+Float_t MCalibrationChargeBlindPix::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
+// 
+Float_t MCalibrationChargeBlindPix::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
+// 
+Float_t MCalibrationChargeBlindPix::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 )
+// 
+Float_t MCalibrationChargeBlindPix::GetLambdaRelVar() const
+{
+  if (fLambdaVar < 0.)
+    return -1.;
+  
+  if (fLambda  == 0.)
+    return -1.;
+  
+  return fLambdaVar / fLambda / fLambda ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkBlindPixelQEGreenErr is smaller than 0.
+// Return -1 if gkBlindPixelQEGreen    is 0.
+// Return gkBlindPixelQEGreenErr^2 / (gkBlindPixelQEGreen^2 )
+// 
+const Float_t MCalibrationChargeBlindPix::GetBlindPixelQEGreenRelVar() const
+{
+  if (gkBlindPixelQEGreenErr < 0.)
+    return -1.;
+  
+  if (gkBlindPixelQEGreen  == 0.)
+    return -1.;
+  
+  return gkBlindPixelQEGreenErr * gkBlindPixelQEGreenErr / gkBlindPixelQEGreen / gkBlindPixelQEGreen ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkBlindPixelQEBlueErr is smaller than 0.
+// Return -1 if gkBlindPixelQEBlue    is 0.
+// Return gkBlindPixelQEBlueErr^2 / gkBlindPixelQEBlue^2
+// 
+const Float_t MCalibrationChargeBlindPix::GetBlindPixelQEBlueRelVar() const
+{
+  if (gkBlindPixelQEBlueErr < 0.)
+    return -1.;
+  
+  if (gkBlindPixelQEBlue  == 0.)
+    return -1.;
+  
+  return gkBlindPixelQEBlueErr * gkBlindPixelQEBlueErr / gkBlindPixelQEBlue / gkBlindPixelQEBlue ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkBlindPixelQEUVErr is smaller than 0.
+// Return -1 if gkBlindPixelQEUV    is 0.
+// Return gkBlindPixelQEUVErr ^2 / gkBlindPixelQEUV^2 
+// 
+const Float_t MCalibrationChargeBlindPix::GetBlindPixelQEUVRelVar() const
+{
+  if (gkBlindPixelQEUVErr < 0.)
+    return -1.;
+  
+  if (gkBlindPixelQEUV  == 0.)
+    return -1.;
+  
+  return gkBlindPixelQEUVErr * gkBlindPixelQEUVErr / gkBlindPixelQEUV / gkBlindPixelQEUV ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return -1 if gkBlindPixelQECT1Err is smaller than 0.
+// Return -1 if gkBlindPixelQECT1    is 0.
+// Return gkBlindPixelQECT1Err ^2 / gkBlindPixelQECT1^2
+// 
+const Float_t MCalibrationChargeBlindPix::GetBlindPixelQECT1RelVar() const
+{
+  if (gkBlindPixelQECT1Err < 0.)
+    return -1.;
+  
+  if (gkBlindPixelQECT1  == 0.)
+    return -1.;
+  
+  return gkBlindPixelQECT1Err * gkBlindPixelQECT1Err / gkBlindPixelQECT1 / gkBlindPixelQECT1 ;
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kChargeFitValid
+//
+Bool_t MCalibrationChargeBlindPix::IsChargeFitValid()  const 
+{
+    return TESTBIT(fFlags,kChargeFitValid);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kOscillating
+//
+Bool_t MCalibrationChargeBlindPix::IsOscillating()  const 
+{
+    return TESTBIT(fFlags,kOscillating);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kPedestalFitValid
+//
+Bool_t MCalibrationChargeBlindPix::IsPedestalFitOK()  const 
+{
+    return TESTBIT(fFlags,kPedestalFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kSinglePheFitValid
+//
+Bool_t MCalibrationChargeBlindPix::IsSinglePheFitOK()  const 
+{
+    return TESTBIT(fFlags,kSinglePheFitOK);
+}
+
+// --------------------------------------------------------------------------
+//
+// Test bit kFluxInsidePlexiglassAvailable
+//
+Bool_t  MCalibrationChargeBlindPix::IsFluxInsidePlexiglassAvailable()   const
+{
+  return TESTBIT(fFlags,kFluxInsidePlexiglassAvailable);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Return kFALSE if IsChargeFitValid() is kFALSE
+//
+// Calculate fFluxInsidePlexiglass with the formula:
+// - fFluxInsidePlexiglass    = fLambda * gkBlindPixelArea / gkBlindPixelQE * 10**gkBlindPixelAtt
+// - fFluxInsidePlexiglassVar = sqrt( fLambdaVar / ( fLambda * fLambda ) 
+//                             + ( gkBlindPixelQEErr * gkBlindPixelQEErr / gkBlindPixelQE / gkBlindPixelQE )
+//                               ) * 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 MCalibrationChargeBlindPix::CalcFluxInsidePlexiglass()
+{
+
+  if (IsChargeFitValid())
+    return kFALSE;
+  
+
+  //
+  // Start calculation of number of photons 
+  // The blind pixel has exactly 100 mm^2 area (with negligible error), 
+  //
+  switch (fColor)
+    {
+    case MCalibrationCam::kGREEN:
+      fFluxInsidePlexiglass    = fLambda * gkBlindPixelQEGreen * TMath::Power(10,gkBlindPixelAttGreen);   
+      // attenuation has negligible error
+      fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetBlindPixelQEGreenRelVar();
+      break;
+    case MCalibrationCam::kBLUE:
+      fFluxInsidePlexiglass    = fLambda * gkBlindPixelQEBlue * TMath::Power(10,gkBlindPixelAttBlue);   
+      // attenuation has negligible error
+      fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetBlindPixelQEBlueRelVar();
+      break;
+    case MCalibrationCam::kUV:
+      fFluxInsidePlexiglass    = fLambda * gkBlindPixelQEUV * TMath::Power(10,gkBlindPixelAttUV);   
+      // attenuation has negligible error
+      fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetBlindPixelQEUVRelVar();
+      break;
+    case MCalibrationCam::kCT1:
+    default:
+      fFluxInsidePlexiglass    = fLambda * gkBlindPixelQECT1 * TMath::Power(10,gkBlindPixelAttCT1);   
+      // attenuation has negligible error
+      fFluxInsidePlexiglassVar = GetLambdaRelVar() + GetBlindPixelQECT1RelVar();
+      break;
+    }
+
+  //
+  // Finish calculation of errors -> convert from relative variance to absolute variance
+  //
+  fFluxInsidePlexiglassVar *= fFluxInsidePlexiglass * fFluxInsidePlexiglass;
+
+  if (fFluxInsidePlexiglass < 0.)
+      return kFALSE;
+
+  if (fFluxInsidePlexiglassVar < 0.)
+      return kFALSE;
+
+  SetFluxInsidePlexiglassAvailable(kTRUE);  
+
+  *fLog << inf << endl;
+  *fLog << inf << " Photon flux [ph/mm^2] inside Plexiglass: " 
+        << Form("%5.3f%s%5.3f",fFluxInsidePlexiglass," +- ",GetFluxInsidePlexiglassErr()) << endl;
+
+  return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeBlindPix.h	(revision 3781)
@@ -0,0 +1,116 @@
+#ifndef MARS_MCalibrationChargeBlindPix
+#define MARS_MCalibrationChargeBlindPix
+
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+
+#ifndef MARS_MCalibrationChargePix
+#include "MCalibrationChargePix.h"
+#endif
+
+class MCalibrationChargeBlindPix : public MCalibrationChargePix
+{
+private:
+
+  static const Float_t gkBlindPixelArea;        //! The Blind Pixel area in mm^2
+  static const Float_t gkBlindPixelAttGreen;    //! Attenuation Filter at 520 nm 
+  static const Float_t gkBlindPixelAttBlue ;    //! Attenuation Filter at 460 nm 
+  static const Float_t gkBlindPixelAttUV   ;    //! Attenuation Filter at 370 nm 
+  static const Float_t gkBlindPixelAttCT1  ;    //! Attenuation Filter at 370 nm
+  static const Float_t gkBlindPixelQEGreen;     //! Quantum Efficiency at 520 nm
+  static const Float_t gkBlindPixelQEBlue ;     //! Quantum Efficiency at 460 nm
+  static const Float_t gkBlindPixelQEUV   ;     //! Quantum Efficiency at 370 nm
+  static const Float_t gkBlindPixelQECT1  ;     //! Quantum Efficiency at 370 nm
+  static const Float_t gkBlindPixelQEGreenErr;  //! Uncertainty QE at 520 nm 
+  static const Float_t gkBlindPixelQEBlueErr ;  //! Uncertainty QE at 460 nm 
+  static const Float_t gkBlindPixelQEUVErr   ;  //! Uncertainty QE at 370 nm 
+  static const Float_t gkBlindPixelQECT1Err  ;  //! Uncertainty QE at 370 nmu
+
+  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 };
+
+  MCalibrationCam::PulserColor_t fColor;  
+
+  const Float_t GetBlindPixelQEGreenRelVar() const; 
+  const Float_t GetBlindPixelQEBlueRelVar () const; 
+  const Float_t GetBlindPixelQEUVRelVar   () const; 
+  const Float_t GetBlindPixelQECT1RelVar  () const; 
+
+ public:
+
+  MCalibrationChargeBlindPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationChargeBlindPix() {}
+  
+  Bool_t CalcFluxInsidePlexiglass();
+  void   Clear(Option_t *o="");
+  
+  // Getters
+  MCalibrationCam::PulserColor_t GetColor () const { return fColor;                }
+  Float_t GetLambda                       () const { return fLambda;               }
+  Float_t GetLambdaErr                    () const;
+  Float_t GetLambdaRelVar                 () const;  
+  Float_t GetLambdaCheck                  () const { return fLambdaCheck;          }
+  Float_t GetLambdaCheckErr               () const { return fLambdaCheckErr;       }
+  Float_t GetFluxInsidePlexiglass         () const { return fFluxInsidePlexiglass; }
+  Float_t GetFluxInsidePlexiglassErr      () const;
+  Float_t GetFluxInsidePlexiglassRelVar   () const;  
+  Float_t GetMu0                          () const { return fMu0;                  }
+  Float_t GetMu0Err                       () const { return fMu0Err;               }
+  Float_t GetMu1                          () const { return fMu1;                  }
+  Float_t GetMu1Err                       () const { return fMu1Err;               }
+  Float_t GetSigma0                       () const { return fSigma0;               }
+  Float_t GetSigma0Err                    () const { return fSigma0Err;            } 
+  Float_t GetSigma1                       () const { return fSigma1;               }
+  Float_t GetSigma1Err                    () const { return fSigma1Err;            }
+
+  Bool_t  IsOscillating                   () const;
+  Bool_t  IsChargeFitValid                () const;
+  Bool_t  IsPedestalFitOK                 () const;
+  Bool_t  IsSinglePheFitOK                () const;
+  Bool_t  IsFluxInsidePlexiglassAvailable () const;
+  
+  // Setters
+  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(MCalibrationChargeBlindPix, 1)	// Container Charge Calibration Results Blind Pixel
+};
+
+#endif
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.cc	(revision 3781)
@@ -0,0 +1,1444 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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()
+//                  - FinalizeBlindPixel()
+//                  - 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 "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawRunHeader.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationChargeBlindPix.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+#include "MExtractedSignalBlindPixel.h"
+#include "MExtractedSignalPINDiode.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationQECam.h"
+#include "MCalibrationQEPix.h"
+
+#include "MCalibrationCam.h"
+
+ClassImp(MCalibrationChargeCalc);
+
+using namespace std;
+
+const Float_t MCalibrationChargeCalc::fgChargeLimit            = 3.;
+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.2;
+const Float_t MCalibrationChargeCalc::fgPheErrLimit            = 5.;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to NULL
+// 
+// Calls AddToBranchList for: 
+// - MRawEvtData.fHiGainPixId   
+// - MRawEvtData.fLoGainPixId   
+// - MRawEvtData.fHiGainFadcSamples
+// - MRawEvtData.fLoGainFadcSamples
+//
+// Initializes:
+// - fChargeLimit       to fgChargeLimit 
+// - fChargeErrLimit    to fgChargeErrLimit   
+// - fChargeRelErrLimit to fgChargeRelErrLimit
+// - fLambdaCheckLimit  to fgLambdaCheckLimit 
+// - fLambdaErrLimit    to fgLambdaErrLimit 
+// - fPheErrLimit       to fgPheErrLimit  
+// - fPulserColor       to MCalibrationCam::kCT1
+// 
+// Calls:
+// - Clear()
+//
+MCalibrationChargeCalc::MCalibrationChargeCalc(const char *name, const char *title)
+    : fBadPixels(NULL), fCam(NULL), fBlindPixel(NULL), fPINDiode(NULL), 
+      fQECam(NULL), fGeom(NULL), fPedestals(NULL), fEvtTime(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();
+  SetLambdaCheckLimit();
+  SetLambdaErrLimit();
+  SetPheErrLimit();
+  SetPulserColor(MCalibrationCam::kNONE);
+
+  Clear();
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - all variables to 0., 
+// - all flags to kFALSE
+//
+void MCalibrationChargeCalc::Clear(const Option_t *o)
+{
+  
+    fNumHiGainSamples        = 0.;
+    fNumLoGainSamples        = 0.;
+    fSqrtHiGainSamples       = 0.;
+    fSqrtLoGainSamples       = 0.;
+    SkipHiLoGainCalibration( kFALSE );    
+}
+
+
+// -----------------------------------------------------------------------------------
+//
+// The following container are searched for and execution aborted if not in MParList:
+//  - MPedestalCam
+//
+// The following containers are searched and created if they were not found:
+//
+//  - MCalibrationQECam
+//  - MBadPixelsCam
+//
+// The following output containers are only searched,  but not created. If they 
+// cannot be found, the corresponding calibration part is only skipped.
+//
+//  - MTime
+//
+Int_t MCalibrationChargeCalc::PreProcess(MParList *pList)
+{
+  
+  // 
+  // Containers that have to be there.
+  //
+  fPedestals = (MPedestalCam*)pList->FindObject("MPedestalCam");
+  if (!fPedestals)
+    {
+      *fLog << err << "MPedestalCam not found... aborting" << endl;
+      return kFALSE;
+    }
+  
+  // 
+  // Containers that are created in case that they are not there.
+  //
+  fQECam = (MCalibrationQECam*)pList->FindCreateObj("MCalibrationQECam");
+  if (!fQECam)
+    {
+      *fLog << err << "Cannot find nor create MCalibrationQECam... aborting" << endl;
+      return kFALSE;
+    }
+
+  fBadPixels = (MBadPixelsCam*)pList->FindCreateObj("MBadPixelsCam");
+  if (!fBadPixels)
+    {
+      *fLog << err << "Could not find or create MBadPixelsCam ... aborting." << endl;
+      return kFALSE;
+    }
+
+  
+  fEvtTime = (MTime*)pList->FindObject("MTime");
+
+  //
+  // Check the pulser colour --> FIXME: this solution is only valid until the arrival of the DM's
+  //
+  if (fPulserColor == MCalibrationCam::kNONE)
+    {
+      *fLog << endl;
+      *fLog << err << GetDescriptor()
+            << ": No Pulser colour has been chosen. Since the installation of the IFAE pulser box,"
+            << " you HAVE to provide the LEDs colour, otherwise there is no calibration. " << endl;
+      *fLog << "See e.g. the macro calibration.C " << endl;
+      return kFALSE;
+    }
+  
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Search for the following input containers and abort if not existing:
+//  - MGeomCam
+//  - MCalibrationChargeCam
+// 
+// Search for the following input containers and give a warning if not existing:
+//  - MCalibrationChargeBlindPix
+//  - MCalibrationChargePINDiode
+//
+// It retrieves the following variables from MCalibrationChargeCam:
+//
+//  - fNumHiGainSamples 
+//  - fNumLoGainSamples 
+//
+// It defines the PixId of every pixel in:
+//
+// - 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
+// - MCalibrationChargeBlindPix (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;
+    }
+  
+  fCam = (MCalibrationChargeCam*)pList->FindObject("MCalibrationChargeCam");
+  if (!fCam)
+    {
+      *fLog << err << "Cannot find MCalibrationChargeCam... aborting" << endl;
+      *fLog << err << "Maybe you forget to call an MFillH for the MHCalibrationChargeCam before..." << endl;
+      return kFALSE;
+    }
+
+  // 
+  // Optional Containers 
+  //
+  fBlindPixel = (MCalibrationChargeBlindPix*)pList->FindObject("MCalibrationChargeBlindPix");
+  if (!fBlindPixel)
+    *fLog << warn << GetDescriptor() 
+          << ": MCalibrationChargeBlindPix not found... no blind pixel method! " << endl;
+  
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindObject("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+    *fLog << warn << GetDescriptor() 
+          << "MCalibrationChargePINDiode not found... no PIN Diode method! " << endl;
+  
+
+  //
+  // Initialize the pulser colours
+  //
+  if (fCam->GetPulserColor() == MCalibrationCam::kNONE)
+    {
+      fCam->SetPulserColor( fPulserColor );
+      
+      if (fBlindPixel)
+        fBlindPixel->SetColor( fPulserColor );
+      
+      if (fPINDiode)
+        fPINDiode->SetColor( fPulserColor );
+    }
+
+  if (fPulserColor != fCam->GetPulserColor())
+    {
+      *fLog << err << GetDescriptor() 
+            << ": Pulser colour has changed w.r.t. last file in MCalibrationChargeCam" << endl;
+      *fLog << err << "This feature is not yet implemented, sorry ... aborting " << endl;
+      return kFALSE;
+    }
+
+  if (fBlindPixel)
+    if (fPulserColor != fBlindPixel->GetColor())
+      {
+        *fLog << err << GetDescriptor() 
+              << ": Pulser colour has changed w.r.t. last file in MCalibrationChargeBlindPix." << endl;
+        *fLog << err << "This feature is not yet implemented, sorry ... aborting " << endl;
+        return kFALSE;
+      }
+  
+  if (fPINDiode)
+    if (fPulserColor != fPINDiode->GetColor())
+      {
+        *fLog << err << GetDescriptor() 
+              << ": Pulser colour has changed w.r.t. last file in MCalibrationChargePINDiode." << endl;
+        *fLog << err << "This feature is not yet implemented, sorry ... aborting " << endl;
+        return kFALSE;
+      }
+  
+
+  fNumHiGainSamples  =  fCam->GetNumHiGainFADCSlices();
+  fNumLoGainSamples  =  fCam->GetNumLoGainFADCSlices();
+  fSqrtHiGainSamples =  TMath::Sqrt(fNumHiGainSamples);
+  fSqrtLoGainSamples =  TMath::Sqrt(fNumLoGainSamples);
+  
+  UInt_t npixels     = fGeom->GetNumPixels();
+  
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)  [i];
+      MCalibrationQEPix     &pqe = (MCalibrationQEPix&)    (*fQECam)[i];
+      MBadPixelsPix         &bad = (*fBadPixels)[i];
+      
+      pix.SetPixId(i);
+      pqe.SetPixId(i);
+      
+      if (bad.IsBad())
+        {
+          pix.SetExcluded();
+          pqe.SetExcluded();
+          continue;
+        }
+      
+    }
+
+  return kTRUE;
+}
+
+// ----------------------------------------------------------------------------------
+//  
+// Nothing to be done in Process, but have a look at MHCalibrationChargeCam, instead
+// 
+Int_t MCalibrationChargeCalc::Process()
+{
+  return kTRUE;
+}
+
+// -----------------------------------------------------------------------
+//
+// Return if number of executions is null.
+//
+// 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 FinalizeBlindPixel() 
+// 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 MParContainer::SetReadyToSave() for fCam, fQECam, fBadPixels and 
+//                                          fBlindPixel and fPINDiode if they exist
+//
+// Print out some statistics
+//
+Int_t MCalibrationChargeCalc::PostProcess()
+{
+
+  if (GetNumExecutions()==0)
+    return kFALSE;
+
+  if (fPINDiode)
+    if (!fPINDiode->IsValid())
+      {
+        *fLog << warn << GetDescriptor() 
+              << ": MCalibrationChargePINDiode is declared not valid... no PIN Diode method! " << endl;
+        fPINDiode = NULL;
+      }
+
+  if (fBlindPixel)
+    if (!fBlindPixel->IsValid())
+      {
+        *fLog << warn << GetDescriptor() 
+              << ": MCalibrationChargeBlindPix is declared not valid... no Blind Pixel method! " << endl;
+        fBlindPixel = NULL;
+      }
+  
+  //
+  // First loop over pixels, call FinalizePedestals and FinalizeCharges
+  //
+  Int_t   nvalid      = 0;
+
+  for (Int_t pixid=0; pixid<fPedestals->GetSize(); pixid++)
+    {
+
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[pixid];
+      //
+      // Check if the pixel has been excluded from the fits
+      //
+      if (pix.IsExcluded())
+        continue;
+
+      MPedestalPix  &ped = (*fPedestals)[pixid];
+      MBadPixelsPix &bad = (*fBadPixels)[pixid];
+
+      FinalizePedestals(ped,pix);
+
+      if (FinalizeCharges(pix,bad))
+        nvalid++;
+    }
+  
+  //
+  // The Michele check ...
+  //
+  if (nvalid == 0)
+  {
+      *fLog << err << GetDescriptor() << ": All pixels have non-valid calibration. " 
+	    << "Did you forget to fill the histograms "
+            << "(filling MHCalibrationChargeCam from MExtractedSignalCam using MFillH) ? " << endl;
+      *fLog << err << 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&)fCam->GetAverageArea(aidx);
+
+      FinalizePedestals(ped,pix);
+      FinalizeCharges(pix, fCam->GetAverageBadArea(aidx));
+    }
+  
+  for (UInt_t sector=0; sector<fGeom->GetNumSectors(); sector++)
+    {
+
+      const MPedestalPix     &ped = fPedestals->GetAverageSector(sector);
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)fCam->GetAverageSector(sector);
+
+      FinalizePedestals(ped,pix);
+      FinalizeCharges(pix, fCam->GetAverageBadSector(sector));
+    }
+  
+  //
+  // Finalize Bad Pixels
+  // 
+  FinalizeBadPixels();
+
+  // 
+  // Finalize F-Factor method
+  //
+  if (!FinalizeFFactorMethod())
+    {
+      *fLog << warn << "Could not calculate the photons flux from the F-Factor method " << endl;
+      fCam->SetFFactorMethodValid(kFALSE); 
+      return kFALSE;
+    }
+  else
+    fCam->SetFFactorMethodValid(kTRUE);
+  
+  // 
+  // Finalize Blind Pixel
+  //
+  if (FinalizeBlindPixel())
+    fQECam->SetBlindPixelMethodValid(kTRUE);
+  else
+    fQECam->SetBlindPixelMethodValid(kFALSE); 
+
+  // 
+  // Finalize PIN Diode
+  //
+  if (FinalizePINDiode())
+    fQECam->SetPINDiodeMethodValid(kTRUE);
+  else
+    fQECam->SetPINDiodeMethodValid(kFALSE); 
+
+  //
+  // Finalize QE Cam
+  //
+  FinalizeFFactorQECam();
+  FinalizeBlindPixelQECam();
+  FinalizePINDiodeQECam();
+
+  fCam      ->SetReadyToSave();
+  fQECam    ->SetReadyToSave();
+  fBadPixels->SetReadyToSave();
+
+  if (fBlindPixel)
+    fBlindPixel->SetReadyToSave();
+  if (fPINDiode)
+    fPINDiode->SetReadyToSave();
+  
+
+  
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Calibration statistics:" << endl;
+  *fLog << dec << setfill(' ');
+
+  UInt_t countinner = 0;
+  UInt_t countouter = 0;  
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+      if (bad.IsOK())
+        {
+          if (fGeom->GetPixRatio(i) == 1.)
+            countinner++;
+          else
+            countouter++;
+        }
+    }
+
+  *fLog << " " << setw(7) << "Successfully calibrated Pixels: " 
+        << "Inner: " << countinner << " Outer: " << countouter << endl;
+  
+  PrintUnsuitable(MBadPixelsPix::kUnsuitableRun, "Bad Pixels:                     ");
+  PrintUnsuitable(MBadPixelsPix::kUnreliableRun, "Unreliable Pixels:              ");
+
+  *fLog << inf << endl;
+  *fLog << GetDescriptor() << ": Errors statistics:" << endl;  
+
+  PrintUncalibrated(MBadPixelsPix::kChargeIsPedestal,    
+                    Form("%s%2.1f%s","Signal less than ",fChargeLimit," Pedestal RMS:                "));
+  PrintUncalibrated(MBadPixelsPix::kChargeErrNotValid, 
+                    Form("%s%2.1f%s","Signal Error smaller than ",fChargeErrLimit,":                    "));
+  PrintUncalibrated(MBadPixelsPix::kChargeRelErrNotValid,
+                    Form("%s%2.1f%s","Signal Error bigger than ",fChargeRelErrLimit," times Mean Signal:   "));
+  PrintUncalibrated(MBadPixelsPix::kChargeSigmaNotValid, 
+                    "Signal Sigma smaller than Pedestal RMS:           ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainSaturation,    
+                    "Pixels with 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::kHiGainOscillating,   
+                    "Pixels with changing Hi Gain signal over time:    ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainOscillating,   
+                    "Pixels with changing Lo Gain signal over time:    ");
+  PrintUncalibrated(MBadPixelsPix::kDeviatingNumPhes,    
+                    "Pixels with deviating number of phes:             ");
+  PrintUncalibrated(MBadPixelsPix::kHiGainNotFitted,     
+                    "Pixels with unsuccesful Gauss fit to the Hi Gain: ");
+  PrintUncalibrated(MBadPixelsPix::kLoGainNotFitted,     
+                    "Pixels with unsuccesful Gauss fit to the Lo Gain: ");
+
+  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)
+{
+  
+  //
+  // get the pedestals
+  //
+  const Float_t pedes  = ped.GetPedestal();
+  const Float_t prms   = ped.GetPedestalRms();
+  const Float_t num    = TMath::Sqrt((Float_t)fPedestals->GetTotalEntries());
+
+  //
+  // set them in the calibration camera
+  //
+  if (cal.IsHiGainSaturation())
+    {
+      cal.SetPedestal(pedes* fNumLoGainSamples,
+                      prms * fSqrtLoGainSamples,
+                      prms * fNumLoGainSamples / num);
+      cal.CalcLoGainPedestal((Float_t)fNumLoGainSamples);
+    }
+  else
+    {
+      cal.SetPedestal(pedes* fNumHiGainSamples,
+                      prms * fSqrtHiGainSamples,
+                      prms * fNumHiGainSamples / num);
+    }
+  
+}
+
+// ----------------------------------------------------------------------------------------------------
+//
+// 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 
+//       if not succesful.
+// 
+// Calls MCalibrationChargePix::CalcFFactorMethod() and sets flag: MBadPixelsPix::kDeviatingNumPhes) 
+//       if not succesful.
+//
+Bool_t MCalibrationChargeCalc::FinalizeCharges(MCalibrationChargePix &cal, MBadPixelsPix &bad)
+{
+
+  if (cal.GetMean() < fChargeLimit*cal.GetPedRms())
+    {
+      *fLog << warn << GetDescriptor() << ": Fitted Charge: " << cal.GetMean() << " is smaller than "
+            << fChargeLimit << " Pedestal RMS: " <<  cal.GetPedRms() << " in Pixel  " << cal.GetPixId() << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeIsPedestal);
+    }
+  
+  if (cal.GetMeanErr() < fChargeErrLimit) 
+    {
+      *fLog << warn << GetDescriptor() << ": Error of Fitted Charge: " << cal.GetMeanErr() 
+            << " is smaller than " << fChargeErrLimit << " in Pixel  " << cal.GetPixId() << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeErrNotValid );
+    }
+      
+   if (cal.GetMean() < fChargeRelErrLimit*cal.GetMeanErr()) 
+    {
+      *fLog << warn << GetDescriptor() << ": Fitted Charge: " << cal.GetMean() << " is smaller than "
+            << fChargeRelErrLimit << "* its error: " << cal.GetMeanErr() 
+            << " in Pixel  " << cal.GetPixId() << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeRelErrNotValid );
+    }
+
+  if (cal.GetSigma() < cal.GetPedRms())
+    {
+      *fLog << warn << GetDescriptor() << ": Sigma of Fitted Charge: " << cal.GetSigma() 
+	    << " smaller than Pedestal RMS: " << cal.GetPedRms() << " in Pixel  " << cal.GetPixId() << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kChargeSigmaNotValid );
+    }
+
+  if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+    return kFALSE;
+
+  if (!cal.CalcReducedSigma())
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Could not calculate reduced sigmas of pixel: " << cal.GetPixId() << endl;
+      bad.SetUncalibrated(MBadPixelsPix::kChargeIsPedestal);
+      return kFALSE;
+    }
+  
+  if (!cal.CalcFFactorMethod())
+    {
+      *fLog << warn << GetDescriptor() 
+            << ": Could not calculate F-Factor of pixel: " << 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::kChargeErrNotValid 
+// - MBadPixelsPix::kChargeRelErrNotValid 
+// - MBadPixelsPix::kChargeSigmaNotValid 
+// - MBadPixelsPix::kMeanTimeInFirstBin 
+// - MBadPixelsPix::kMeanTimeInLast2Bins 
+//
+// Sets pixel to MBadPixelsPix::kUnreliableRun, if one of the following flags is set:
+// - MBadPixelsPix::kDeviatingNumPhes
+//
+void MCalibrationChargeCalc::FinalizeBadPixels()
+{
+  
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      
+      MBadPixelsPix    &bad    = (*fBadPixels)[i];
+
+      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 (bad.IsUncalibrated( MBadPixelsPix::kChargeSigmaNotValid ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInFirstBin ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kMeanTimeInLast2Bins ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kDeviatingNumPhes ))
+        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 or 
+//             MBadPixelsPix::kUnreliableRun (see FinalizeBadPixels()) and set 
+//             MCalibrationChargePix::SetFFactorMethodValid(kFALSE) in that case.
+//              
+// Second loop: Get weighted 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.
+// 
+//              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() )
+// 
+Bool_t MCalibrationChargeCalc::FinalizeFFactorMethod()
+{
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  Float_t lowlim      [nareas];
+  Float_t upplim      [nareas];
+  Float_t areavars    [nareas];
+  Float_t areaweights [nareas], sectorweights [nsectors];
+  Float_t areaphes    [nareas], sectorphes    [nsectors];
+  Int_t   numareavalid[nareas], numsectorvalid[nsectors];
+
+  memset(lowlim        ,0, nareas   * sizeof(Float_t));
+  memset(upplim        ,0, nareas   * sizeof(Float_t));
+  memset(areaphes      ,0, nareas   * sizeof(Float_t));
+  memset(areavars      ,0, nareas   * sizeof(Float_t));
+  memset(areaweights   ,0, nareas   * sizeof(Float_t));
+  memset(numareavalid  ,0, nareas   * sizeof(Int_t  ));
+  memset(sectorweights ,0, nsectors * sizeof(Float_t));
+  memset(sectorphes    ,0, nsectors * sizeof(Float_t));
+  memset(numsectorvalid,0, nsectors * sizeof(Int_t  ));
+  
+  //
+  // First loop: Get mean number of photo-electrons and the RMS
+  //             The loop is only to recognize later pixels with very deviating numbers
+  //
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)  [i];
+      MBadPixelsPix         &bad = (*fBadPixels)[i];
+      
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnsuitableRun))
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      if (bad.IsUnsuitable(MBadPixelsPix::kUnreliableRun))
+        continue;
+      
+      const Float_t nphe  = pix.GetPheFFactorMethod();
+      const Float_t nvar  = pix.GetPheFFactorMethodVar();
+      const Int_t   aidx  = (*fGeom)[i].GetAidx();
+
+      if (nvar > 0.)
+        {
+          areaphes    [aidx] += nphe;
+          areavars    [aidx] += nvar;
+          numareavalid[aidx] ++;
+        } 
+    } 
+
+  for (UInt_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;
+        }
+
+      areaphes[i] = areaphes[i] / numareavalid[i];
+      areavars[i] = areavars[i] / numareavalid[i];
+      lowlim  [i] = areaphes[i] - fPheErrLimit*TMath::Sqrt(areavars[i]);
+      upplim  [i] = areaphes[i] + fPheErrLimit*TMath::Sqrt(areavars[i]);
+    }
+
+  memset(numareavalid,0,nareas*sizeof(Int_t));
+  memset(areaphes    ,0,nareas*sizeof(Int_t));
+  memset(areavars    ,0,nareas*sizeof(Int_t));
+
+  //
+  // Second loop: Get weighted 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 (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+
+      if (!pix.IsFFactorMethodValid())
+        continue;
+
+      const Float_t nvar  = pix.GetPheFFactorMethodVar();
+
+      if (nvar <= 0.)
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+      
+      MBadPixelsPix         &bad = (*fBadPixels)[i];
+
+      const Int_t   aidx   = (*fGeom)[i].GetAidx();
+      const Int_t   sector = (*fGeom)[i].GetSector();
+      const Float_t nphe   = pix.GetPheFFactorMethod();
+
+      if ( nphe < lowlim[aidx] || nphe > upplim[aidx] )
+        {
+          *fLog << warn << GetDescriptor() << ": Deviating number of photo-electrons: " 
+                << Form("%4.2f",nphe) << " out of accepted limits: [" 
+                << Form("%4.2f%s%4.2f",lowlim[aidx],",",upplim[aidx]) << "] in pixel " << i << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+          bad.SetUnsuitable  ( MBadPixelsPix::kUnreliableRun    );
+          continue;
+        }
+      
+      const Float_t weight = 1./nvar;
+      
+      areaweights   [aidx]   += weight;
+      areaphes      [aidx]   += weight*nphe;
+      numareavalid  [aidx]   ++;
+      sectorweights [sector] += weight;
+      sectorphes    [sector] += weight*nphe;
+      numsectorvalid[sector] ++;
+    } 
+
+  for (UInt_t aidx=0; aidx<nareas; aidx++)
+    {
+
+      MCalibrationChargePix &apix = (MCalibrationChargePix&)fCam->GetAverageArea(aidx);
+
+      if (areaweights[aidx] <= 0. || areaphes[aidx] <= 0.)
+        {
+          *fLog << warn << " Mean number of phe's from area index " << aidx << " cannot be calculated: "
+                << " Sum of weights: "       << areaweights[aidx] 
+                << " Sum of weighted phes: " << areaphes[aidx]    << endl;
+          apix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      *fLog << inf << "Replacing number photo-electrons of average area idx " << aidx << ": " 
+            << Form("%5.3f%s%5.3f",apix.GetPheFFactorMethod()," +- ",apix.GetPheFFactorMethodErr()) << endl;
+      *fLog << inf << "  by average number of photo-electrons from area idx " << aidx <<  ": " 
+            << Form("%5.3f%s%5.3f",areaphes[aidx] / areaweights[aidx]," +- ",
+                    TMath::Sqrt(1./areaweights[aidx])) << endl;
+
+      apix.SetPheFFactorMethod   ( areaphes[aidx]/ areaweights[aidx] );
+      apix.SetPheFFactorMethodVar(    1.         / areaweights[aidx] );      
+      apix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  for (UInt_t sector=0; sector<nsectors; sector++)
+    {
+
+      MCalibrationChargePix &spix = (MCalibrationChargePix&)fCam->GetAverageSector(sector);
+
+      if (sectorweights[sector] <= 0. || sectorphes[sector] <= 0.)
+        {
+          *fLog << warn << " Mean number of phe's from sector " << sector << " cannot be calculated: "
+                << " Sum of weights: "       << sectorweights[sector] 
+                << " Sum of weighted phes: " << sectorphes[sector]    << endl;
+          spix.SetFFactorMethodValid(kFALSE);
+          continue;
+        }
+
+      *fLog << inf << "Replacing number photo-electrons of average sector " << sector << ": " 
+            << Form("%5.3f%s%5.3f",spix.GetPheFFactorMethod()," +- ",spix.GetPheFFactorMethodErr()) << endl;
+      *fLog << inf << "   by average number photo-electrons from sector " << sector <<  ": " 
+            << Form("%5.3f%s%5.3f",sectorphes[sector]/ sectorweights[sector]," +- ",
+                    TMath::Sqrt(1./sectorweights[sector])) << endl;
+
+      spix.SetPheFFactorMethod   ( sectorphes[sector]/ sectorweights[sector] );
+      spix.SetPheFFactorMethodVar(    1.        / sectorweights[sector] );      
+      spix.SetFFactorMethodValid ( kTRUE );
+
+    }
+
+  return kTRUE;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Returns kFALSE if pointer to MCalibrationChargeBlindPix 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:
+// - MCalibrationChargeBlindPix::CalcFluxInsidePlexiglass()
+//
+Bool_t MCalibrationChargeCalc::FinalizeBlindPixel()
+{
+
+  if (!fBlindPixel)
+    return kFALSE;  
+
+  const Float_t lambda      = fBlindPixel->GetLambda();
+  const Float_t lambdaerr   = fBlindPixel->GetLambdaErr();
+  const Float_t lambdacheck = fBlindPixel->GetLambdaCheck();
+
+  if (2.*(lambdacheck-lambda)/(lambdacheck+lambda) < fLambdaCheckLimit)
+    {
+      *fLog << warn << GetDescriptor() << ": Lambda and Lambda-Check differ by more than "
+            << fLambdaCheckLimit << " in the Blind Pixel " << endl;
+      return kFALSE;
+    }
+  
+  if (lambdaerr < fLambdaErrLimit) 
+    {
+      *fLog << warn << GetDescriptor() << ": Error of Fitted Lambda is greater than "
+            << fLambdaErrLimit << " in Blind Pixel " << endl;
+      return kFALSE;
+    }
+      
+  if (!fBlindPixel->CalcFluxInsidePlexiglass())
+    {
+      *fLog << warn << "Could not calculate the flux of photons from the Blind Pixel, "
+            << "will skip Blind Pixel Calibration " << endl;
+      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) 
+//                            / MCalibrationQECam::GetPlexiglassQE()
+//
+// Calculate the variance on the average number of photons.
+//
+// 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()
+{
+
+  MCalibrationChargePix &avpix = (MCalibrationChargePix&)fCam->GetAverageArea(0);
+  MCalibrationQEPix     &qepix = (MCalibrationQEPix&)  fQECam->GetAverageArea(0);  
+
+  const Float_t avphotons   = avpix.GetPheFFactorMethod()       
+                           / qepix.GetQEFFactor(fPulserColor)
+                           / fQECam->GetPlexiglassQE();
+
+  const Float_t avphotrelvar = avpix.GetPheFFactorMethodRelVar() 
+                            + qepix.GetQEFFactorRelVar(fPulserColor)
+                            + fQECam->GetPlexiglassQERelVar();
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+      MCalibrationQEPix   &qepix = (MCalibrationQEPix&)  (*fQECam)[i];
+
+      if (!pix.IsFFactorMethodValid())
+        {
+          qepix.SetFFactorMethodValid(kFALSE,fPulserColor);
+          continue;
+        }
+      
+      const Float_t photons = avphotons / fGeom->GetPixRatio(i);
+      const Float_t qe      = pix.GetPheFFactorMethod() / photons ;
+
+      if (!pix.CalcMeanFFactor( photons , avphotrelvar ))
+        {
+          pix.SetFFactorMethodValid(kFALSE);
+          qepix.SetFFactorMethodValid(kFALSE, fPulserColor);
+          (*fBadPixels)[i].SetUncalibrated( MBadPixelsPix::kDeviatingNumPhes );
+        }
+
+      const Float_t qerelvar = avphotrelvar +  pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEFFactor    ( qe            , fPulserColor );
+      qepix.SetQEFFactorVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.SetFFactorMethodValid(  kTRUE   , fPulserColor );
+
+      if (!qepix.UpdateFFactorMethod())
+        *fLog << warn << GetDescriptor() 
+              << ": Cannot update Quantum efficiencies with the F-Factor Method" << endl;
+    }
+}
+
+
+// ------------------------------------------------------------------------
+//
+// Loop over pixels: 
+//
+// - Continue, if not MCalibrationChargeBlindPix::IsFluxInsidePlexiglassAvailable() and set:
+//                    MCalibrationQEPix::SetBlindPixelMethodValid(kFALSE,fPulserColor)
+//
+// - Calculate the quantum efficiency with the formula:
+// 
+//   QE =  Num.Phes / MCalibrationChargeBlindPix::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()
+{
+
+  const UInt_t npixels  = fGeom->GetNumPixels();
+  
+  //
+  //  With the knowledge of the overall photon flux, calculate the 
+  //  quantum efficiencies after the Blind Pixel and PIN Diode method
+  //
+  for (UInt_t i=0; i<npixels; i++)
+    {
+      
+      MCalibrationQEPix   &qepix = (MCalibrationQEPix&)  (*fQECam)[i];
+
+      if (!fBlindPixel)
+        {
+          qepix.SetBlindPixelMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      if (!fBlindPixel->IsFluxInsidePlexiglassAvailable())
+        {
+          qepix.SetBlindPixelMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      MBadPixelsPix       &bad   =                   (*fBadPixels)[i];
+
+      if (!bad.IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetBlindPixelMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[i];
+      MGeomPix              &geo =                        (*fGeom)[i];
+      
+      const Float_t qe        = pix.GetPheFFactorMethod() 
+                             / fBlindPixel->GetFluxInsidePlexiglass() 
+                             / geo.GetA() 
+                            * fQECam->GetPlexiglassQE();
+
+      const Float_t qerelvar = fBlindPixel->GetFluxInsidePlexiglassRelVar() 
+                               + fQECam->GetPlexiglassQERelVar()
+                               + pix.GetPheFFactorMethodRelVar();
+
+      qepix.SetQEBlindPixel    ( qe            , fPulserColor );
+      qepix.SetQEBlindPixelVar ( qerelvar*qe*qe, fPulserColor );      
+      qepix.UpdateBlindPixelMethod();
+    }
+}
+
+// ------------------------------------------------------------------------
+//
+// 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();
+
+  //
+  //  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&)  (*fQECam)[i];
+
+      if (!fPINDiode)
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      if (!fPINDiode->IsFluxOutsidePlexiglassAvailable())
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+
+      MBadPixelsPix &bad  =  (*fBadPixels)[i];
+
+      if (!bad.IsUnsuitable (MBadPixelsPix::kUnsuitableRun))
+        {
+          qepix.SetPINDiodeMethodValid(kFALSE, fPulserColor);
+          continue;
+        }
+      
+      MCalibrationChargePix &pix = (MCalibrationChargePix&)(*fCam)[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.UpdateBlindPixelMethod();
+    }
+}
+
+// -----------------------------------------------------------------------------------------------
+//
+// Print out statistics about BadPixels of type UnsuitableType_t 
+// 
+void MCalibrationChargeCalc::PrintUnsuitable(MBadPixelsPix::UnsuitableType_t typ, const char *text) const 
+{
+
+  UInt_t countinner = 0;
+  UInt_t countouter = 0;
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*fBadPixels)[i];
+      if (bad.IsUnsuitable(typ))
+        {
+          if (fGeom->GetPixRatio(i) == 1.)
+            countinner++;
+          else
+            countouter++;
+        }
+    }
+
+  *fLog << " " << setw(7) << text 
+        << Form("%s%3i%s%3i","Inner: ",countinner," Outer: ",countouter) << 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;
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      MBadPixelsPix &bad = (*fBadPixels)[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;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCalc.h	(revision 3781)
@@ -0,0 +1,118 @@
+#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
+
+class MRawEvtData;
+class MRawRunHeader;
+class MPedestalCam;
+class MPedestalPix;
+class MCalibrationChargePINDiode;
+class MCalibrationChargeBlindPix;
+class MCalibrationChargePix;
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MGeomCam;
+class MExtractedSignalCam;
+class MExtractedSignalBlindPixel;
+class MExtractedSignalPINDiode;
+class MBadPixelsCam;
+class MBadPixelsPix;
+class MTime;
+class MCalibrationChargeCalc : public MTask
+{
+private:
+
+  static const Float_t fgChargeLimit;          //! Default for fChargeLimit       (now set to: 3.)
+  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.2)
+  static const Float_t fgPheErrLimit;          //! Default for fPheErrLimit       (now set to: 5.)
+
+  // 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)
+  Byte_t  fFlags;                              // Bit-field for the flags
+  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 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 
+
+  // Pointers
+  MBadPixelsCam              *fBadPixels;      //  Bad Pixels 
+  MCalibrationChargeCam      *fCam;            //  Calibrated Charges of all pixels 
+  MCalibrationChargeBlindPix *fBlindPixel;     //  Calibrated Charges of the Blind Pixel 
+  MCalibrationChargePINDiode *fPINDiode;       //  Calibrated Charges of the PIN Diode
+  MCalibrationQECam          *fQECam;          //  Calibrated Quantum Efficiencies of all pixels 
+  MGeomCam                   *fGeom;           //! Camera geometry
+  MPedestalCam               *fPedestals;      //! Pedestals all pixels (calculated previously from ped.file)
+  MTime                      *fEvtTime;        //! Time of the event
+
+  // enums
+  enum  { kHiLoGainCalibration };
+
+  // functions
+  void   FinalizePedestals      ( const MPedestalPix &ped, MCalibrationChargePix &cal );
+  Bool_t FinalizeCharges        ( MCalibrationChargePix &cal, MBadPixelsPix &bad      );
+  Bool_t FinalizePINDiode       ();
+  Bool_t FinalizeBlindPixel     ();
+  Bool_t FinalizeFFactorMethod  ();
+  void   FinalizeBadPixels      ();
+  void   FinalizeFFactorQECam   ();  
+  void   FinalizeBlindPixelQECam();
+  void   FinalizePINDiodeQECam  ();
+  
+  void   PrintUnsuitable  ( MBadPixelsPix::UnsuitableType_t typ  , const char *text) const;   
+  void   PrintUncalibrated( MBadPixelsPix::UncalibratedType_t typ, const char *text) const;
+
+  Int_t  PreProcess (MParList *pList);
+  Bool_t ReInit     (MParList *pList); 
+  Int_t  Process    ();
+  Int_t  PostProcess();
+
+public:
+
+  MCalibrationChargeCalc(const char *name=NULL, const char *title=NULL);
+
+  void Clear(const Option_t *o="");
+  
+  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;   }
+  void SetLambdaErrLimit    ( const Float_t f=fgLambdaErrLimit         ) { fLambdaErrLimit    = f;   }
+  void SetLambdaCheckLimit  ( const Float_t f=fgLambdaCheckLimit       ) { fLambdaCheckLimit  = f;   }
+  void SetPheErrLimit       ( const Float_t f=fgPheErrLimit            ) { fPheErrLimit       = f;   }  
+  void SetPulserColor       ( const MCalibrationCam::PulserColor_t col ) { fPulserColor       = col; }
+
+  void SkipHiLoGainCalibration ( const Bool_t b=kTRUE )
+      { b ? CLRBIT(fFlags, kHiLoGainCalibration) : SETBIT(fFlags, kHiLoGainCalibration); }
+
+  ClassDef(MCalibrationChargeCalc, 1)   // Task calculating Calibration Containers and Quantum Efficiencies
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.cc	(revision 3781)
@@ -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): 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. 
+//
+// The following "calibration" constants are used for the calibration of each pixel 
+// (see MCalibrate and MCalibrateData):
+//
+// - 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              
+//           MCalibrationChargeBlindPix, MCalibrationChargePINDiode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationCam.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MCalibrationChargePix.h"
+#include "MCalibrationChargeBlindPix.h"
+#include "MCalibrationChargePINDiode.h"
+
+ClassImp(MCalibrationChargeCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets all pointers to 0
+// 
+// Creates a TClonesArray of MCalibrationChargePix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationChargeCam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationChargePix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationChargeCam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationChargePix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationChargeCam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+// 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";
+  
+  fPixels           = new TClonesArray("MCalibrationChargePix",1);
+  fAverageAreas     = new TClonesArray("MCalibrationChargePix",1);
+  fAverageSectors   = new TClonesArray("MCalibrationChargePix",1);
+  
+  Clear();
+}
+
+
+// --------------------------------------
+//
+// Sets all variable to 0.
+// Sets all flags to kFALSE
+// Calls MCalibrationCam::Clear()
+//
+void MCalibrationChargeCam::Clear(Option_t *o)
+{
+
+  SetFFactorMethodValid    ( kFALSE );
+
+  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 << "Pix " << pix->GetPixId() 
+                << ":  Ped.  Rms: "            << pix->GetPedRms()        << " +- " << pix->GetPedRmsErr() 
+		<< "   Mean signal: "          << pix->GetMean()    << " +- " << pix->GetSigma() 
+		<< "   Reduced Sigma: "        << pix->GetRSigma() 
+		<< "   Nr Phe's: "             << pix->GetPheFFactorMethod() 
+                << " Saturated? :" << pix->IsHiGainSaturation() 
+		<< 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() << endl;
+	  id++;
+      }
+  }
+  *fLog << all << id << " Excluded pixels " << endl;
+  *fLog << endl;
+
+  TIter Next5(fAverageAreas);
+  while ((pix=(MCalibrationChargePix*)Next5()))
+  {
+    *fLog << all << "Average Area:" 
+          << "   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;
+  }
+
+  TIter Next6(fAverageSectors);
+  while ((pix=(MCalibrationChargePix*)Next5()))
+  {
+    *fLog << all << "Average Sector:" 
+          << "   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;
+  }
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// 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())
+//
+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.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;
+    case 5:
+      if (pix.IsExcluded())
+        return kFALSE;
+      if (pix.GetRSigma() == -1.)
+	  return kFALSE;
+      val = pix.GetRSigma();
+      break;
+    case 6:
+      if (pix.IsExcluded())
+        return kFALSE;    
+      if (pix.GetRSigma() == -1.)
+	  return kFALSE;
+      val = pix.GetRSigmaErr();
+      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;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MCalibrationChargePix::DrawClone()
+//
+void MCalibrationChargeCam::DrawPixelContent(Int_t idx) const
+{
+  MCalibrationChargePix &pix = (MCalibrationChargePix&)(*this)[idx];
+  pix.DrawClone();
+}
+
+
+
+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;
+}
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargeCam.h	(revision 3781)
@@ -0,0 +1,39 @@
+#ifndef MARS_MCalibrationChargeCam
+#define MARS_MCalibrationChargeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationChargeCam : public MCalibrationCam
+{
+private:
+  
+  Byte_t  fFlags;                    // Bit-field to hold the flags
+
+  enum  { kFFactorMethodValid };
+
+public:
+
+  MCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  
+  void   Clear ( Option_t *o="" );
+  
+  // Draws
+  void   DrawPixelContent(Int_t num)   const;    
+
+  // 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;
+  Bool_t IsFFactorMethodValid()      const;
+
+  // Prints
+  void   Print(Option_t *o="")         const;
+
+  // Setters   
+  void   SetFFactorMethodValid (const Bool_t b=kTRUE );
+
+  ClassDef(MCalibrationChargeCam, 1) // Container Charge Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.cc	(revision 3781)
@@ -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: 100.000 +- 10 mm^2 
+//
+// Ratio of areas: 
+//
+// Distance of PIN Diode to pulser D1:   1.5  +- 0.3 m
+// Distance of Inner Pixel to pulser D2: 18.0 +- 0.5 m
+//
+//                          D1*D1
+// gkSolidAngleRatio   =   -------- = 0.00007
+//                         Ap*D2*D2
+//
+// gkSolidAngleRatioErr = 0.00002
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationChargePix.h"
+
+#include "MCalibrationCam.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::gkSolidAngleRatio      = 0.00007;
+const Float_t MCalibrationChargePINDiode::gkSolidAngleRatioErr   = 0.00002;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreen    = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlue     = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUV       = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1      = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEGreenErr = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEBlueErr  = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQEUVErr    = -1.0;
+const Float_t MCalibrationChargePINDiode::gkPINDiodeQECT1Err   = -1.0;
+// --------------------------------------------------------------------------
+//
+// 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-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePINDiode.h	(revision 3781)
@@ -0,0 +1,113 @@
+#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 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-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.cc	(revision 3781)
@@ -0,0 +1,818 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 CalcFFactorMethod() )
+//
+// 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: GetConvertedLoGainMean() or GetConvertedLoGainSigma()
+// 
+// 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.5;
+const Float_t MCalibrationChargePix::gkElectronicPedRmsErr      = 0.3;
+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    = 5.;
+const Float_t MCalibrationChargePix::fgConvFFactorRelErrLimit   = 0.35;
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Sets:
+// - fCalibFlags to 0
+// - fConversionHiLo to fgConversionHiLo
+// - fConversionHiLoVar to square of fgConversionHiLoErr
+// - fConvFFactorRelErrLimit to fgConvFFactorRelErrLimit*fgConvFFactorRelErrLimit
+// - 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;
+}
+
+// -------------------------------------------------------------------------------
+//
+// 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 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 Error of the Mean pedestals: 
+// Returns square root of fPedVar
+//
+Float_t  MCalibrationChargePix::GetPedErr()  const
+{
+  return  TMath::Sqrt(fPedVar);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 converted to High Gain amplification: 
+// Returns fLoGainMean multiplied with fConversionHiLo
+//
+Float_t MCalibrationChargePix::GetConvertedLoGainMean()  const 
+{
+  return fLoGainMean * fConversionHiLo;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 GetConvertedLoGainMean()
+//
+Float_t MCalibrationChargePix::GetConvertedLoGainMeanErr()  const
+{
+
+  const Float_t logainrelvar = GetLoGainMeanRelVar();
+  
+  if (logainrelvar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(logainrelvar + GetConversionHiLoRelVar()) * GetConvertedLoGainMean();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Low Gain Sigma converted to High Gain amplification: 
+// Returns fLoGainSigma multiplied with fConversionHiLo
+//
+Float_t MCalibrationChargePix::GetConvertedLoGainSigma()  const 
+{
+  return fLoGainSigma * fConversionHiLo;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Error of the converted Low Gain Sigma: 
+//
+// Returns -1 if the variable fLoGainSigma or fLoGainSigmaVar are smaller than 0.
+//
+// Returns the square root of the quadratic sum of the relative variances of 
+// the fLoGainSigma and fConversionHiLo, mulitplied with GetConvertedLoGainSigma()
+//
+Float_t MCalibrationChargePix::GetConvertedLoGainSigmaErr()  const
+{
+
+  if (fLoGainSigmaVar < 0.)
+    return -1.;
+
+  if (fLoGainSigma < 0.)
+    return -1.;
+
+  const Float_t sigmaRelVar     =  fLoGainSigmaVar
+                                /( fLoGainSigma * fLoGainSigma );
+
+  return TMath::Sqrt(sigmaRelVar+GetConversionHiLoRelVar()) * GetConvertedLoGainSigma();
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Get the 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::GetRSigma()  const
+{
+  if (fRSigmaSquare < 0)
+    return -1;
+
+  const Float_t rsigma = TMath::Sqrt(fRSigmaSquare);
+  
+  return IsHiGainSaturation() ? rsigma*fConversionHiLo : rsigma ;
+} 
+
+// --------------------------------------------------------------------------
+//
+// 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
+// - 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::GetRSigmaErr()  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 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::GetRSigmaSquare()  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)
+  //
+  const Float_t rsigmaRelVar = 0.25 * fRSigmaSquareVar / ( fRSigmaSquare * fRSigmaSquare );
+
+  if (IsHiGainSaturation())
+    return rsigmaRelVar + GetConversionHiLoRelVar();
+  else
+    return rsigmaRelVar;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+  const Float_t sigmaSquare    =      sigma     * sigma;
+  const Float_t sigmaSquareVar = 4. * sigmavar  * sigmaSquare;
+
+  //
+  // Calculate the reduced sigmas
+  //
+  fRSigmaSquare = sigmaSquare - pedRmsSquare;
+  if (fRSigmaSquare <= 0.)
+    {
+      *fLog << warn 
+            << "WARNING: Cannot calculate the reduced sigma: smaller than 0 in pixel " 
+            << fPixId << endl;
+      return kFALSE;
+    }
+
+  fRSigmaSquareVar = 4. * (sigmaSquareVar + pedRmsSquareVar);
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------
+//
+// If fRSigmaSquare is smaller than 0 (i.e. has not yet been set),
+// set kFFactorMethodValid to kFALSE and 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
+//   else: Set kFFactorMethodValid to kTRUE and return kTRUE
+//
+Bool_t MCalibrationChargePix::CalcFFactorMethod()
+{
+
+  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 (fPheFFactorMethod < fPheFFactorMethodLimit)
+    return kFALSE;
+  
+  //
+  // Calculate the Error of Nphe
+  //
+  const Float_t pheRelVar = ffactorsquareRelVar + meanSquareRelVar + rsigmaSquareRelVar;
+  fPheFFactorMethodVar =  pheRelVar * fPheFFactorMethod * fPheFFactorMethod;
+
+  if (fPheFFactorMethodVar < 0. )
+    return kFALSE;
+
+  fMeanConvFADC2Phe    =  fPheFFactorMethod / GetMean();
+  
+  if (fMeanConvFADC2Phe < 0. )
+    return kFALSE;
+  
+  //
+  // 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:
+  // 
+  const Float_t convrelvar = ffactorsquareRelVar + GetMeanRelVar() + rsigmaSquareRelVar;
+
+  if (convrelvar > fConvFFactorRelVarLimit || convrelvar < 0.)
+    {
+      *fLog << warn << GetDescriptor() << ": Conversion F-Factor Method Rel. Variance: " 
+            << convrelvar << " above limits of: [0," << Form("%3.2f",fConvFFactorRelVarLimit)
+            << "] in pixel: " << 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 (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 (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;
+
+  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  = gkElectronicPedRmsErr * gkElectronicPedRmsErr * logainsamples;
+  
+  Float_t pedRmsSquare      = fPedRms * fPedRms;
+  Float_t pedRmsSquareVar   = fPedVar * pedRmsSquare; // fPedRmsErr = fPedErr/2.
+  
+  //
+  // We do not know the Lo Gain Pedestal RMS, so we have to retrieve it 
+  // from the HI GAIN (all calculation per slice up to now):  
+  //
+  // We extract the pure NSB contribution:
+  //
+  const Float_t elecRmsSquare    =    elecPedRms    * elecPedRms;
+  const Float_t elecRmsSquareVar = 4.*elecPedRmsVar * elecRmsSquare;
+  
+  Float_t higainNsbSquare        =  pedRmsSquare    - elecRmsSquare;
+  Float_t higainNsbSquareRelVar  = (pedRmsSquareVar + elecRmsSquareVar)
+                                 / (higainNsbSquare * higainNsbSquare) ;
+  
+  if (higainNsbSquare < 0.)
+    higainNsbSquare = 0.;
+  
+  //
+  // 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;
+  const Float_t logainNsbSquareVar      = ( higainNsbSquareRelVar + conversionSquareRelVar )
+                                	  * logainNsbSquare * logainNsbSquare;
+    
+  fLoGainPedRmsSquare    = logainNsbSquare    + elecRmsSquare;
+  fLoGainPedRmsSquareVar = logainNsbSquareVar + elecRmsSquareVar;
+}
+ 
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationChargePix.h	(revision 3781)
@@ -0,0 +1,112 @@
+#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 (now set to: 1.5)
+  static const Float_t gkElectronicPedRmsErr;    //! Error Electr. component ped. RMS (now set to: 0.3)
+  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 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 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 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 GetConvertedLoGainMean     () const;
+  Float_t GetConvertedLoGainMeanErr  () const;
+  Float_t GetConvertedLoGainSigma    () const;
+  Float_t GetConvertedLoGainSigmaErr () 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;
+  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 GetRSigmaPerCharge         () const;
+  Float_t GetRSigmaPerChargeErr      () const;
+  Float_t GetRSigmaSquare            () const;  
+  Float_t GetRSigmaRelVar            () const;
+
+  Bool_t IsFFactorMethodValid        () const;
+
+  // Calculations
+  void   CalcLoGainPedestal       ( const Float_t logainsamples  );
+  Bool_t CalcReducedSigma  ();
+  Bool_t CalcFFactorMethod ();
+  Bool_t CalcMeanFFactor   ( const Float_t nphotons, const Float_t nphotonsrelvar );
+  
+  ClassDef(MCalibrationChargePix, 1)	// Container Charge Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.cc	(revision 3781)
@@ -0,0 +1,145 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 "MCalibrationCam.h"
+
+#include <TClonesArray.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";
+
+    fPixels           = new TClonesArray("MCalibrationPix",1);
+    fAverageAreas     = new TClonesArray("MCalibrationPix",1);
+    fAverageSectors   = new TClonesArray("MCalibrationPix",1);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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].GetMean();
+      break;
+    case 1:
+      val = (*this)[idx].GetMeanErr();
+      break;
+    case 2:
+      val = (*this)[idx].GetSigma();
+      break;
+    case 3:
+      val = (*this)[idx].GetSigmaErr();
+      break;
+    case 4:
+      val = (*this)[idx].GetProb();
+      break;
+    default:
+      return kFALSE;
+    }
+
+  return val!=-1.;
+  
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPedCam.h	(revision 3781)
@@ -0,0 +1,23 @@
+#ifndef MARS_MCalibrationPedCam
+#define MARS_MCalibrationPedCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationPedCam : public MCalibrationCam
+{
+private:
+  
+  
+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-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.cc	(revision 3781)
@@ -0,0 +1,393 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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.;
+  fHiGainSigma         =  -1.;
+  fHiGainSigmaVar      =  -1.;
+
+  fLoGainNumBlackout   =  -1 ;
+  fLoGainNumPickup     =  -1 ;
+  fLoGainMean          =  -1.;
+  fLoGainMeanVar       =  -1.;
+  fLoGainProb          =  -1.;
+  fLoGainSigma         =  -1.;
+  fLoGainSigmaVar      =  -1.;
+
+  SetHiGainSaturation  ( kFALSE );
+  SetExcluded          ( kFALSE );
+  SetValid             ( kFALSE );
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the Hi Gain Saturation Bit from outside
+//
+void MCalibrationPix::SetHiGainSaturation(Bool_t b)
+{
+    b ?  SETBIT(fFlags, kHiGainSaturation) : CLRBIT(fFlags, kHiGainSaturation); 
+}
+
+
+// --------------------------------------------------------------------------
+//
+// 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 zero or -1. (has not yet been set)
+// 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. || fLoGainMean == -1.)
+    return -1.;
+
+  if (fHiGainMean == -1.)
+    return -1.;
+  
+  return fHiGainMean / fLoGainMean;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Mean or its variance is zero or -1. (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. || fLoGainMean == -1.)
+    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 zero or -1. (has not yet been set)
+// 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. || fLoGainSigma == -1.)
+    return -1.;
+
+  if (fHiGainSigma == -1.)
+    return -1.;
+  
+  return fHiGainSigma / fLoGainSigma;
+  
+}
+
+// ----------------------------------------------------------------------------------
+//
+// Return -1, if IsHiGainSaturation()
+// Return -1, if the LoGain Sigma or its variance is zero or -1. (has not yet been set)
+// 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. || fLoGainSigma == -1.)
+    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.)
+      return -1.;
+    else
+      return fLoGainMeanVar / (fLoGainMean * fLoGainMean);
+  else
+    if (fHiGainMeanVar < 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 (fLoGainMeanVar < 0.)
+    return -1.;
+
+  return TMath::Sqrt(fLoGainMeanVar);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// 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 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 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-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationPix.h	(revision 3781)
@@ -0,0 +1,109 @@
+#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 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 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 };   // Possible bits to be sets
+
+public:
+
+  MCalibrationPix(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationPix() {}
+  
+  virtual void Clear(Option_t *o="");
+
+  // 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 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 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 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 GetHiGainProb       () const { return fHiGainProb   ;     }
+  Float_t GetHiGainSigma      () const { return fHiGainSigma  ;     }
+  Float_t GetHiGainSigmaErr   () const;
+  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 GetLoGainMeanRelVar () const;  
+  virtual Float_t GetLoGainProb       () const { return fLoGainProb;        }
+  virtual Float_t GetLoGainSigma      () const { return fLoGainSigma;       }
+  virtual Float_t GetLoGainSigmaErr   () const;
+  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 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  IsExcluded()         const;
+  Bool_t  IsValid   ()         const;
+
+  ClassDef(MCalibrationPix, 1)	// Base Container for Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.cc	(revision 3781)
@@ -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): 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 "MCalibrationCam.h"
+
+#include <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationQEPix.h"
+
+ClassImp(MCalibrationQECam);
+
+using namespace std;
+
+const Float_t MCalibrationQECam::gkPlexiglassQE         = 0.96;
+const Float_t MCalibrationQECam::gkPlexiglassQEErr      = 0.01;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibrationQEPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel. Later, a call to MCalibrationQECam::InitSize() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationQEPix containers, initialized to 1 entry, destinated 
+// to hold one container per pixel AREA. Later, a call to MCalibrationQECam::InitAreas() 
+// has to be performed (in MGeomApply). 
+//
+// Creates a TClonesArray of MCalibrationQEPix containers, initialized to 1 entry, destinated
+// to hold one container per camera SECTOR. Later, a call to MCalibrationQECam::InitSectors() 
+// has to be performed (in MGeomApply). 
+//
+MCalibrationQECam::MCalibrationQECam(const char *name, const char *title)
+    : fFlags(MCalibrationCam::gkNumPulserColors)
+{
+    fName  = name  ? name  : "MCalibrationQECam";
+    fTitle = title ? title : "Storage container for the calibrated Quantrum Efficiency of the camera";
+
+    fPixels           = new TClonesArray("MCalibrationQEPix",1);
+    fAverageAreas     = new TClonesArray("MCalibrationQEPix",1);
+    fAverageSectors   = new TClonesArray("MCalibrationQEPix",1);
+
+    Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// 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();
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Not yet implemented
+//
+void MCalibrationQECam::DrawPixelContent(Int_t idx) const
+{
+  return;
+}
+
+// --------------------------------------------------------------------
+//
+// 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:
+      val = pix.GetQECascadesFFactor();
+      break;
+    case 1:
+      val = pix.GetQECascadesFFactorErr();
+      break;
+    case 2:
+      val = pix.GetQECascadesBlindPixel();
+      break;
+    case 3:
+      val = pix.GetQECascadesBlindPixelErr();
+      break;
+    case 4:
+      val = pix.GetQECascadesPINDiode();
+      break;
+    case 5:
+      val = pix.GetQECascadesPINDiodeErr();
+      break;
+    case 6:
+      val = pix.GetQECascadesCombined();
+      break;
+    case 7:
+      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);    
+}
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQECam.h	(revision 3781)
@@ -0,0 +1,69 @@
+#ifndef MARS_MCalibrationQECam
+#define MARS_MCalibrationQECam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+#ifndef ROOT_TArrayC
+#include "TArrayC.h"
+#endif
+
+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;
+
+  enum { kBlindPixelMethodValid, kFFactorMethodValid,
+         kPINDiodeMethodValid, kCombinedMethodValid };
+
+public:
+
+  MCalibrationQECam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationQECam() {}
+
+  void    Clear( Option_t *o="");
+  
+  // Others
+  void    DrawPixelContent( Int_t num ) const;    
+  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; 
+
+  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, 1) // Container Quantum Efficieny Calibration Results Camera
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.cc	(revision 3781)
@@ -0,0 +1,1172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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.96
+//
+// * 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
+// 
+// * 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.
+//
+//  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 teh entrance window cross section. So, in 
+//  first approximation, no loses when increasing light incidence angle; 
+//  and therefore, the factor 0.94."
+//
+// See also: MJCalibration, MCalibrationChargeCalc, 
+//           MCalibrationChargeCam, MCalibrationChargePix, 
+//           MHCalibrationChargeCam, MHCalibrationChargePix,
+//           MHCalibrationChargePINDiode, MHCalibrationChargeBlindPix
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MCalibrationQEPix.h"
+#include "MCalibrationCam.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "TArrayF.h"
+#include "TArrayC.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.05 ;
+const Float_t MCalibrationQEPix::gkDefaultQEBlueErr    = 0.07 ;
+const Float_t MCalibrationQEPix::gkDefaultQEUVErr      = 0.07 ;
+const Float_t MCalibrationQEPix::gkDefaultQECT1Err     = 0.07 ;
+const Float_t MCalibrationQEPix::gkDefaultAverageQE    = 0.18;     
+const Float_t MCalibrationQEPix::gkDefaultAverageQEErr = 0.02;  
+// --------------------------------------------------------------------------
+//
+// Default Constructor: 
+//
+// Initializes all TArrays to MCalibrationCam::gkNumPulserColors
+//
+// Calls:
+// - Clear()
+//
+MCalibrationQEPix::MCalibrationQEPix(const char *name, const char *title)
+    :  fQEBlindPixel    ( MCalibrationCam::gkNumPulserColors), 
+       fQEBlindPixelVar ( MCalibrationCam::gkNumPulserColors ),
+       fQECombined      ( MCalibrationCam::gkNumPulserColors ),    
+       fQECombinedVar   ( MCalibrationCam::gkNumPulserColors ), 
+       fQEFFactor       ( MCalibrationCam::gkNumPulserColors ),     
+       fQEFFactorVar    ( MCalibrationCam::gkNumPulserColors ),  
+       fQEPINDiode      ( MCalibrationCam::gkNumPulserColors ),    
+       fQEPINDiodeVar   ( MCalibrationCam::gkNumPulserColors ),
+       fAverageQE       ( gkDefaultAverageQE ), 
+       fValidFlags      ( MCalibrationCam::gkNumPulserColors )
+{
+
+  fName  = name  ? name  : "MCalibrationQEPix";
+  fTitle = title ? title : "Container of the calibrated quantum efficiency ";
+
+  Clear();
+
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// 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) ; 
+    const Float_t newavqevar = ( GetQEBlindPixelRelVar(col) + GetDefaultQERelVar(col) ) * newavqe * newavqe;
+    wav  += newavqe / newavqevar;
+    sumw += 1. / newavqevar ;
+  }
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// Search all available QE's of a certain colour after the combination of the three methods
+// 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::AddAverageCombinedQEs(const MCalibrationCam::PulserColor_t col, Float_t &wav, Float_t &sumw )
+{
+
+  if (IsCombinedMethodValid (col))
+  {
+    const Float_t newavqe    =   GetQECombined(col)       / GetDefaultQE (col) ; 
+    const Float_t newavqevar = ( GetQECombinedRelVar(col) + GetDefaultQERelVar(col) ) * newavqe * newavqe;
+    wav  += newavqe / newavqevar;
+    sumw += 1./ newavqevar;
+
+  }
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// 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) ; 
+    const Float_t newavqevar = ( GetQEFFactorRelVar(col) + GetDefaultQERelVar(col) ) * newavqe * newavqe;
+    wav  += newavqe / newavqevar;
+    sumw += 1./ newavqevar;
+
+  }
+
+
+}
+
+// ----------------------------------------------------------------------------------------------
+// 
+// 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) ; 
+    const Float_t newavqevar = ( GetQEPINDiodeRelVar(col) + GetDefaultQERelVar(col) ) * newavqe * newavqe;
+    wav  += newavqe / newavqevar;
+    sumw += 1./ newavqevar;
+  }
+}
+
+
+
+// ------------------------------------------------------------------------
+//
+// 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)
+//
+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)
+//
+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)
+//
+const Float_t MCalibrationQEPix::GetAvNormBlindPixelRelVar( ) const 
+{
+  return fAvNormBlindPixelVar / (fAvNormBlindPixel * fAvNormBlindPixel ); 
+}
+
+// -----------------------------------------------------------------
+//
+// Return the relative variance of the average normalization (Combined Method)
+//
+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)
+//
+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 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);
+}
+
+// ------------------------------------------------------------------------------
+//
+// 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[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],kBlindPixelMethodValid);
+  else
+    CLRBIT(fValidFlags[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],kCombinedMethodValid);
+  else
+    CLRBIT(fValidFlags[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],kFFactorMethodValid);
+  else
+    CLRBIT(fValidFlags[ MCalibrationCam::kGREEN ],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[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);
+  else
+    CLRBIT(fValidFlags[ MCalibrationCam::kGREEN ],kPINDiodeMethodValid);    
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Blind Pixel Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateBlindPixelMethod()
+{
+
+  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;
+
+  weightedav /= sumweights;
+
+  fAvNormBlindPixel     = gkDefaultAverageQE   *  weightedav;
+  fAvNormBlindPixelVar  = GetAverageQERelVar() + (sumweights / weightedav / weightedav );  
+  fAvNormBlindPixelVar *= fAvNormBlindPixel * fAvNormBlindPixel;
+
+  return kTRUE;
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the Combination of the three Methods: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateCombinedMethod()
+{
+  
+  Float_t weightedav = 0.;
+  Float_t sumweights = 0.;
+
+  AddAverageCombinedQEs(MCalibrationCam::kGREEN, weightedav, sumweights);
+  AddAverageCombinedQEs(MCalibrationCam::kBLUE , weightedav, sumweights);
+  AddAverageCombinedQEs(MCalibrationCam::kUV   , weightedav, sumweights);
+  AddAverageCombinedQEs(MCalibrationCam::kCT1  , weightedav, sumweights);
+
+  if (weightedav == 0. || sumweights == 0.)
+    return kFALSE;
+
+  weightedav /= sumweights;
+
+  fAvNormCombined     = gkDefaultAverageQE   *  weightedav;
+  fAvNormCombinedVar  = GetAverageQERelVar() + (sumweights / weightedav / weightedav );  
+  fAvNormCombinedVar *= fAvNormCombined * fAvNormCombined;
+
+  return kTRUE;
+  
+}
+
+// ------------------------------------------------------------------------------
+//
+// Update the F-Factor Method: Calculate new average QE's
+//
+Bool_t  MCalibrationQEPix::UpdateFFactorMethod()
+{
+
+  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 / 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;
+
+  weightedav /= sumweights;
+
+  fAvNormPINDiode     = gkDefaultAverageQE   *  weightedav;
+  fAvNormPINDiodeVar  = GetAverageQERelVar() + (sumweights / weightedav / weightedav );  
+  fAvNormPINDiodeVar *= fAvNormPINDiode * fAvNormPINDiode;
+
+  return kTRUE;
+
+  
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationQEPix.h	(revision 3781)
@@ -0,0 +1,162 @@
+#ifndef MARS_MCalibrationQEPix
+#define MARS_MCalibrationQEPix
+
+#ifndef MARS_MCalibrationPix
+#include "MCalibrationPix.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include "TArrayF.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)
+  
+  TArrayF fQEBlindPixel;                     // Calibrated QEs    (Blind Pixel Method)
+  TArrayF fQEBlindPixelVar;                  // Variance cal. QEs (Blind Pixel Method)
+  TArrayF fQECombined;                       // Calibrated QEs    (Combined Method)
+  TArrayF fQECombinedVar;                    // Variance cal. QEs (Combined Method)
+  TArrayF fQEFFactor;                        // Calibrated QEs    (F-Factor Method)
+  TArrayF fQEFFactorVar;                     // Variance cal. QEs (F-Factor Method)
+  TArrayF fQEPINDiode;                       // Calibrated QEs    (PIN Diode Method)
+  TArrayF 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  AddAverageCombinedQEs  ( 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="");
+  
+  // 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 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;  
+
+  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();
+  Bool_t  UpdateCombinedMethod  ();
+  Bool_t  UpdateFFactorMethod   ();
+  Bool_t  UpdatePINDiodeMethod  ();
+
+  ClassDef(MCalibrationQEPix, 1)     // Container Quantum Efficieny Calibration Results Pixel
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.cc	(revision 3781)
@@ -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): 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 <TClonesArray.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCalibrationRelTimePix.h"
+
+ClassImp(MCalibrationRelTimeCam);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Creates a TClonesArray of MCalibrationRelTimePix 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 MCalibrationRelTimePix 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 MCalibrationRelTimePix 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). 
+//
+MCalibrationRelTimeCam::MCalibrationRelTimeCam(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MCalibrationRelTimeCam";
+    fTitle = title ? title : "Storage container for the Calibration Information in the camera";
+
+    fPixels           = new TClonesArray("MCalibrationRelTimePix",1);
+    fAverageAreas     = new TClonesArray("MCalibrationRelTimePix",1);
+    fAverageSectors   = new TClonesArray("MCalibrationRelTimePix",1);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MCalibrationPix::DrawClone()
+//
+void MCalibrationRelTimeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimeCam.h	(revision 3781)
@@ -0,0 +1,27 @@
+#ifndef MARS_MCalibrationRelTimeCam
+#define MARS_MCalibrationRelTimeCam
+
+#ifndef MARS_MCalibrationCam
+#include "MCalibrationCam.h"
+#endif
+
+class MCalibrationRelTimeCam : public MCalibrationCam
+{
+private:
+  
+public:
+
+  MCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MCalibrationRelTimeCam() {}
+
+  // 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;
+  void DrawPixelContent(Int_t num) const;    
+  
+  ClassDef(MCalibrationRelTimeCam, 1)	// Container Rel. Arrival Time Calibration Results Camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.cc	(revision 3781)
@@ -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): 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-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MCalibrationRelTimePix.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.cc	(revision 3781)
@@ -0,0 +1,914 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 TObjArray'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 TObjArray'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 MHGausEvents.
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationCam.h"
+
+#include <TVirtualPad.h>
+#include <TCanvas.h>
+#include <TPad.h>
+#include <TText.h>
+#include <TPaveText.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MCalibrationPix.h"
+#include "MCalibrationCam.h"
+
+#include "MHGausEvents.h"
+
+#include "MBadPixelsPix.h"
+#include "MBadPixelsCam.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MParList.h"
+
+ClassImp(MHCalibrationCam);
+
+using namespace std;
+
+const Int_t   MHCalibrationCam::fgAverageNbins    = 2000;
+const Int_t   MHCalibrationCam::fgPulserFrequency = 500;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes and sets owner of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+// Initializes:
+// - fPulserFrequency to fgPulserFrequency
+//
+MHCalibrationCam::MHCalibrationCam(const char *name, const char *title)
+    :  fBadPixels(NULL), fCam(NULL), fGeom(NULL)
+{
+    fName  = name  ? name  : "MHCalibrationCam";
+    fTitle = title ? title : "Class to fill the calibration histograms ";
+
+    fHiGainArray = new TObjArray;
+    fHiGainArray->SetOwner();
+    
+    fLoGainArray = new TObjArray;
+    fLoGainArray->SetOwner();
+
+    fAverageHiGainAreas = new TObjArray;
+    fAverageHiGainAreas->SetOwner();
+
+    fAverageLoGainAreas = new TObjArray;
+    fAverageLoGainAreas->SetOwner();
+
+    fAverageHiGainSectors = new TObjArray;
+    fAverageHiGainSectors->SetOwner();
+
+    fAverageLoGainSectors = new TObjArray;
+    fAverageLoGainSectors->SetOwner();
+
+    SetAverageNbins();
+    SetPulserFrequency();
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the TClonesArray of:
+// - fHiGainArray, fLoGainArray
+// - fAverageHiGainAreas, fAverageLoGainAreas
+// - fAverageHiGainSectors, fAverageLoGainSectors
+//
+MHCalibrationCam::~MHCalibrationCam()
+{
+  delete fHiGainArray;
+  delete fLoGainArray;
+
+  delete fAverageHiGainAreas;
+  delete fAverageLoGainAreas;
+
+  delete fAverageHiGainSectors;
+  delete fAverageLoGainSectors;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+MHGausEvents &MHCalibrationCam::operator[](UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fHiGainArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel (pixel number)
+//
+const MHGausEvents &MHCalibrationCam::operator[](UInt_t i) const
+{
+  return *static_cast<MHGausEvents*>(fHiGainArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+MHGausEvents  &MHCalibrationCam::operator()(UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fLoGainArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel (pixel number)
+//
+const MHGausEvents  &MHCalibrationCam::operator()(UInt_t i) const
+{
+  return *static_cast<MHGausEvents*>(fLoGainArray->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TObjArray fAverageHiGainAreas
+// independently if the MHGausEvents is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageAreas() const
+{
+  return fAverageHiGainAreas->GetEntries();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+MHGausEvents  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fAverageHiGainAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain pixel Area (area number)
+//
+const MHGausEvents  &MHCalibrationCam::GetAverageHiGainArea(UInt_t i) const
+{
+  return *static_cast<MHGausEvents *>(fAverageHiGainAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+MHGausEvents  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fAverageLoGainAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain pixel Area (area number)
+//
+const MHGausEvents  &MHCalibrationCam::GetAverageLoGainArea(UInt_t i) const
+{
+  return *static_cast<MHGausEvents*>(fAverageLoGainAreas->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Returns the current size of the TObjArray fAverageHiGainSectors
+// independently if the MHGausEvents is filled with values or not.
+//
+const Int_t MHCalibrationCam::GetAverageSectors() const
+{
+  return fAverageHiGainSectors->GetEntries();
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+MHGausEvents  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fAverageHiGainSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th High Gain Sector (sector number)
+//
+const MHGausEvents  &MHCalibrationCam::GetAverageHiGainSector(UInt_t i) const
+{
+  return *static_cast<MHGausEvents*>(fAverageHiGainSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+MHGausEvents  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i)
+{
+  return *static_cast<MHGausEvents*>(fAverageLoGainSectors->UncheckedAt(i));
+}
+
+// --------------------------------------------------------------------------
+//
+// Get i-th Low Gain Sector (sector number)
+//
+const MHGausEvents  &MHCalibrationCam::GetAverageLoGainSector(UInt_t i) const
+{
+  return *static_cast<MHGausEvents*>(fAverageLoGainSectors->UncheckedAt(i));
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Our own clone function is necessary since root 3.01/06 or Mars 0.4
+// I don't know the reason. 
+//
+// Creates new MHCalibrationCam
+// Deletes the TObjArray's and Clones them individually
+// Copies the TArray's
+// Copies the fPulserFrequency
+//
+TObject *MHCalibrationCam::Clone(const char *) const
+{
+
+  const Int_t nhi   = fHiGainArray->GetEntries();
+  const Int_t nlo   = fLoGainArray->GetEntries();
+  const Int_t navhi = fAverageHiGainAreas->GetEntries();
+  const Int_t navlo = fAverageLoGainAreas->GetEntries();
+  const Int_t nsehi = fAverageHiGainSectors->GetEntries();
+  const Int_t nselo = fAverageLoGainSectors->GetEntries();
+  
+  //
+  // FIXME, this might be done faster and more elegant, by direct copy.
+  //
+  MHCalibrationCam *cam = new MHCalibrationCam();
+
+  cam->fHiGainArray->Expand(nhi);
+  cam->fLoGainArray->Expand(nlo);
+  cam->fAverageHiGainAreas->Expand(navhi);
+  cam->fAverageLoGainAreas->Expand(navlo);
+  cam->fAverageHiGainSectors->Expand(nsehi);
+  cam->fAverageLoGainSectors->Expand(nselo);
+
+  for (int i=0; i<nhi; i++)
+    {
+      delete (*cam->fHiGainArray)[i];
+      (*cam->fHiGainArray)[i] = (*fHiGainArray)[i]->Clone();
+    }
+  for (int i=0; i<nlo; i++)
+    {
+      delete (*cam->fLoGainArray)[i];
+      (*cam->fLoGainArray)[i] = (*fLoGainArray)[i]->Clone();
+    }
+  for (int i=0; i<navhi; i++)
+    {
+      delete (*cam->fAverageHiGainAreas)[i];
+      (*cam->fAverageHiGainAreas)[i] = (*fAverageHiGainAreas)[i]->Clone();
+    }
+  for (int i=0; i<navlo; i++)
+    {
+      delete (*cam->fAverageLoGainAreas)[i];
+      (*cam->fAverageLoGainAreas)[i] = (*fAverageLoGainAreas)[i]->Clone();
+    }
+  for (int i=0; i<nsehi; i++)
+    {
+      delete (*cam->fAverageHiGainSectors)[i];
+      (*cam->fAverageHiGainSectors)[i] = (*fAverageHiGainSectors)[i]->Clone();
+    }
+  for (int i=0; i<nselo; i++)
+    {
+      delete (*cam->fAverageLoGainSectors)[i];
+      (*cam->fAverageLoGainSectors)[i] = (*fAverageLoGainSectors)[i]->Clone();
+    }
+
+  cam->fAverageAreaNum         = fAverageAreaNum;
+  cam->fAverageAreaSat         = fAverageAreaSat;
+  cam->fAverageAreaSigma       = fAverageAreaSigma;      
+  cam->fAverageAreaSigmaVar    = fAverageAreaSigmaVar;   
+  cam->fAverageAreaRelSigma    = fAverageAreaRelSigma;
+  cam->fAverageAreaRelSigmaVar = fAverageAreaRelSigmaVar;   
+  cam->fAverageSectorNum       = fAverageSectorNum;      
+
+  cam->fPulserFrequency        = fPulserFrequency;
+
+  return cam;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 << "MGeomCam not found... aborting." << endl;
+      return kFALSE;
+  }
+
+  fHiGainArray->Delete();
+  fLoGainArray->Delete();
+
+  fAverageHiGainAreas->Delete();
+  fAverageLoGainAreas->Delete();
+
+  fAverageHiGainSectors->Delete();
+  fAverageLoGainSectors->Delete();
+
+  return SetupHists(pList);
+}
+
+
+Bool_t MHCalibrationCam::SetupHists(const MParList *pList)
+{
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - 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
+// 
+Bool_t MHCalibrationCam::ReInit(MParList *pList)
+{
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  fBadPixels = (MBadPixelsCam*)pList->FindObject("MBadPixelsCam");
+  if (!fBadPixels)
+    {
+
+      fBadPixels = (MBadPixelsCam*)pList->FindCreateObj(AddSerialNumber("MBadPixelsCam"));
+      if (!fBadPixels)
+        {
+          gLog << err << "Cannot find nor create MBadPixelsCam ... abort." << endl;
+          return kFALSE;
+        }
+      else 
+        fBadPixels->InitSize(npixels);
+    }
+
+  //
+  // 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 i=0; i<npixels; i++)
+    {
+
+      if ((*fBadPixels)[i].IsBad())
+        continue;
+
+      fAverageAreaNum  [(*fGeom)[i].GetAidx()  ]++;
+      fAverageSectorNum[(*fGeom)[i].GetSector()]++;
+    }
+
+  return ReInitHists(pList);
+}
+
+
+Bool_t MHCalibrationCam::ReInitHists(MParList *pList)
+{
+  return kTRUE;
+}
+
+
+
+//--------------------------------------------------------------------------------
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TObjArray's (including the averaged ones), the following steps are performed: 
+//
+// 1) Test size and return kFALSE if not matching
+// 2) 
+//
+Bool_t MHCalibrationCam::Fill(const MParContainer *par, const Stat_t w)
+{
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nareas   = fGeom->GetNumAreas();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  
+  if (fHiGainArray->GetEntries() != npixels)
+    {
+      gLog << err << "ERROR - Size mismatch... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (fLoGainArray->GetEntries() != npixels)
+    {
+      gLog << err << "ERROR - Size mismatch... abort." << endl;
+      return kFALSE;
+    }
+  
+  if (fAverageHiGainAreas->GetEntries() != nareas)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+      return kFALSE;
+    }
+
+  if (fAverageLoGainAreas->GetEntries() != nareas)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of areas ... abort." << endl;
+      return kFALSE;
+    }
+
+  if (fAverageHiGainSectors->GetEntries() != nsectors)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+      return kFALSE;
+    }
+
+  if (fAverageLoGainSectors->GetEntries() != nsectors)
+    {
+      *fLog << err << "ERROR - Size mismatch in number of sectors ... abort." << endl;
+      return kFALSE;
+    }
+
+  return FillHists(par, w);
+}
+
+Bool_t MHCalibrationCam::FillHists(const MParContainer *par, const Stat_t w)
+{
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 1) FinalizeHists()
+// 2) FinalizeBadPixels()
+// 3) CalcAverageSigma()
+//
+Bool_t MHCalibrationCam::Finalize()
+{
+  if (!FinalizeHists())
+    return kFALSE;
+
+  FinalizeBadPixels();
+  CalcAverageSigma();
+
+  return kTRUE;
+}
+
+Bool_t MHCalibrationCam::FinalizeHists()
+{
+  return kTRUE;
+}
+
+void MHCalibrationCam::FinalizeBadPixels()
+{
+}
+
+
+// -------------------------------------------------------------
+//
+// If MBadPixelsPix::IsBad():
+// - calls MHGausEvents::SetExcluded()
+//
+// Calls:
+// - MHGausEvents::InitBins()
+// - MHGausEvents::ChangeHistId(i)
+// - MHGausEvents::SetEventFrequency(fPulserFrequency)
+// 
+void MHCalibrationCam::InitHists(MHGausEvents &hist, MBadPixelsPix &bad, const Int_t i)
+{
+
+  if (bad.IsBad())
+    hist.SetExcluded();
+  
+  hist.InitBins();
+  hist.ChangeHistId(i);
+  hist.SetEventFrequency(fPulserFrequency);
+          
+}
+
+void MHCalibrationCam::FitHiGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                       MBadPixelsPix::UncalibratedType_t fittyp, 
+                                       MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHGausEvents &hist = (*this)[i];
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+      
+    }
+
+  for (Int_t j=0; j<fAverageHiGainAreas->GetSize(); j++)
+    {
+      
+      MHGausEvents     &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++)
+    {
+      
+      MHGausEvents     &hist = GetAverageHiGainSector(j);      
+      MCalibrationPix  &pix  = calcam.GetAverageSector(j);
+      MBadPixelsPix    &bad  = calcam.GetAverageBadSector(j);        
+      
+      FitHiGainHists(hist,pix,bad,fittyp,osctyp);
+    }
+
+}
+
+void MHCalibrationCam::FitLoGainArrays(MCalibrationCam &calcam, MBadPixelsCam &badcam,
+                                            MBadPixelsPix::UncalibratedType_t fittyp, 
+                                            MBadPixelsPix::UncalibratedType_t osctyp)
+{
+  
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHGausEvents &hist = (*this)(i);
+      
+      if (hist.IsExcluded())
+        continue;
+      
+      MCalibrationPix &pix    = calcam[i];
+      MBadPixelsPix   &bad    = badcam[i];
+      
+      FitLoGainHists(hist,pix,bad,fittyp,osctyp);
+      
+    }
+
+  for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+    {
+      
+      MHGausEvents     &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++)
+    {
+      
+      MHGausEvents     &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()
+{
+  
+  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 MHGausEvents::RepeatFit(), in case of repeated failure 
+// calls MHGausEvents::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(MHGausEvents &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+
+  if (hist.IsEmpty())
+    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 );
+      }
+  
+  hist.Renorm();
+  //
+  // 4) Check for oscillations
+  // 
+  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.SetHiGainSigma      ( hist.GetSigma()     );
+  pix.SetHiGainSigmaVar   ( hist.GetSigmaErr()* hist.GetSigmaErr()  );
+  pix.SetHiGainProb       ( hist.GetProb()      );
+  pix.SetHiGainNumBlackout( hist.GetBlackout()  );
+  pix.SetHiGainNumPickup  ( hist.GetPickup()    );
+  
+}
+
+
+// ---------------------------------------------------------------------------
+//
+// 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 MHGausEvents::RepeatFit(), in case of repeated failure 
+// calls MHGausEvents::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(MHGausEvents &hist, 
+                                      MCalibrationPix &pix, 
+                                      MBadPixelsPix &bad, 
+                                      MBadPixelsPix::UncalibratedType_t fittyp,
+                                      MBadPixelsPix::UncalibratedType_t osctyp)
+{
+
+  if (hist.IsEmpty())
+      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
+  // 
+  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.SetLoGainSigma      ( hist.GetSigma()     );
+  pix.SetLoGainSigmaVar   ( hist.GetSigmaErr() * hist.GetSigmaErr()  );
+  pix.SetLoGainProb       ( hist.GetProb()      );
+  pix.SetLoGainNumBlackout( hist.GetBlackout()  );
+  pix.SetLoGainNumPickup  ( hist.GetPickup()    );
+  
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Dummy, needed by MCamEvent
+//
+Bool_t MHCalibrationCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// What MHCamera needs in order to draw an individual pixel in the camera
+//
+void MHCalibrationCam::DrawPixelContent(Int_t idx) const
+{
+}
+
+// -----------------------------------------------------------------------------
+// 
+// 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)
+{
+
+  const Int_t nareas = fAverageHiGainAreas->GetEntries();
+  if (nareas == 0)
+    return;
+
+  TVirtualPad *pad = gPad ? gPad : MH::MakeDefCanvas(this);  
+  pad->SetBorderMode(0);
+
+  pad->Divide(2,nareas);
+
+  for (Int_t i=0; i<nareas;i++) 
+    {
+
+      pad->cd(2*(i+1)-1);
+      GetAverageHiGainArea(i).Draw(opt);
+
+      if (!fAverageAreaSat[i])
+        DrawAverageSigma(fAverageAreaSat[i], i,
+                         fAverageAreaSigma[i],    fAverageAreaSigmaVar[i],
+                         fAverageAreaRelSigma[i], fAverageAreaRelSigmaVar[i]);
+
+      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.07);
+      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);
+    }
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationCam.h	(revision 3781)
@@ -0,0 +1,152 @@
+#ifndef MARS_MHCalibrationCam
+#define MARS_MHCalibrationCam
+
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef MARS_MBadPixelsPix
+#include "MBadPixelsPix.h"
+#endif
+
+class TText;
+class TArrayI;
+class TArrayF;
+class MHGausEvents;
+class MGeomCam;
+class MCalibrationCam;
+class MCalibrationPix;
+class MBadPixelsCam;
+class MBadPixelsPix;
+class MHCalibrationCam : public MH, public MCamEvent
+{
+  
+private:
+
+  static const Int_t fgAverageNbins;     //! The default for fAverageNbins    (now set to: 2000)
+  static const Int_t fgPulserFrequency;  //! The default for fPulserFrequency (now set to: 500)
+
+protected:
+
+  TArrayI    fAverageAreaNum;           // Number of pixels in average pixels per area
+  TArrayF    fAverageAreaRelSigma;      // Re-normalized relative sigmas in average pixels per area
+  TArrayF    fAverageAreaRelSigmaVar;   // Variance Re-normalized relative sigmas in average pixels per area
+  TArrayI    fAverageAreaSat;           // Number of saturated slices in average pixels per area
+  TArrayF    fAverageAreaSigma;         // Re-normalized sigmas in average pixels per area
+  TArrayF    fAverageAreaSigmaVar;      // Variance Re-normalized sigmas in average pixels per area
+  Int_t      fAverageNbins;             // Number of bins for the average histograms
+  TObjArray *fAverageHiGainAreas;       //-> Array of calibration pixels, one per pixel area
+  TObjArray *fAverageHiGainSectors;     //-> Array of calibration pixels, one per camera sector
+  TObjArray *fAverageLoGainAreas;       //-> Array of calibration pixels, one per pixel area
+  TObjArray *fAverageLoGainSectors;     //-> Array of calibration pixels, one per camera sector
+  TArrayI    fAverageSectorNum;         // Number of pixels in average pixels per sector 
+  
+  MBadPixelsCam    *fBadPixels;         //!  Bad Pixels storage container
+  MCalibrationCam  *fCam;               //!  Calibration Cam with the results
+  MGeomCam         *fGeom;              //!  Camera geometry
+
+  TObjArray *fHiGainArray;              //-> Array of calibration pixels, one per pixel
+  TObjArray *fLoGainArray;              //-> Array of calibration pixels, one per pixel
+
+  Int_t      fPulserFrequency;          // Light pulser frequency
+
+  virtual Bool_t SetupHists(const MParList *pList);
+  virtual Bool_t ReInitHists(MParList *pList);  
+  virtual Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  virtual Bool_t FinalizeHists();
+  virtual void   FinalizeBadPixels();
+  
+  void CalcAverageSigma();
+  
+  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(MHGausEvents &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(MHGausEvents &hist, 
+                      MCalibrationPix &pix, 
+                      MBadPixelsPix &bad, 
+                      MBadPixelsPix::UncalibratedType_t fittyp,
+                      MBadPixelsPix::UncalibratedType_t osctyp);
+
+  void InitHists(MHGausEvents &hist, MBadPixelsPix &bad, const Int_t i);
+
+public:
+
+  MHCalibrationCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationCam();
+
+  virtual Bool_t SetupFill(const MParList *pList);
+  virtual Bool_t ReInit   (      MParList *pList);
+  virtual Bool_t Fill     (const MParContainer *par, const Stat_t w=1);
+  virtual Bool_t Finalize ( );
+
+  // Clone
+  TObject *Clone(const char *) const;
+
+  // Draw
+  virtual void   Draw(const Option_t *opt);
+
+  virtual Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  virtual void   DrawPixelContent( Int_t num )  const;    
+
+  const Int_t          GetAverageAreas       ()          const;	 
+        MHGausEvents  &GetAverageHiGainArea  (UInt_t i);
+  const MHGausEvents  &GetAverageHiGainArea  (UInt_t i)  const;
+        MHGausEvents  &GetAverageLoGainArea  (UInt_t i);
+  const MHGausEvents  &GetAverageLoGainArea  (UInt_t i)  const;
+        MHGausEvents  &GetAverageHiGainSector(UInt_t i);
+  const MHGausEvents  &GetAverageHiGainSector(UInt_t i)  const;
+        MHGausEvents  &GetAverageLoGainSector(UInt_t i);
+  const MHGausEvents  &GetAverageLoGainSector(UInt_t i)  const;
+  const Int_t          GetAverageSectors     ()          const;
+
+        MHGausEvents  &operator[]            (UInt_t i);
+  const MHGausEvents  &operator[]            (UInt_t i)  const;
+        MHGausEvents  &operator()            (UInt_t i);
+  const MHGausEvents  &operator()            (UInt_t i)  const;
+ 
+  void SetAverageNbins(   const Int_t bins=fgAverageNbins ) { fAverageNbins = bins; }
+  void SetPulserFrequency(const Int_t f=fgPulserFrequency)  { fPulserFrequency = f; }
+  
+  ClassDef(MHCalibrationCam, 1)	// Base Histogram class for Calibration Camera
+};
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.cc	(revision 3781)
@@ -0,0 +1,1024 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 ChangeFitFunc().
+//
+//  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 <TVector.h>
+#include <TF1.h>
+#include <TH1.h>
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalBlindPixel.h"
+#include "MCalibrationChargeBlindPix.h"
+
+ClassImp(MHCalibrationChargeBlindPix);
+
+using namespace std;
+
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmp      = 0.008;
+const Double_t MHCalibrationChargeBlindPix::gkElectronicAmpErr   = 0.002;
+
+const Int_t    MHCalibrationChargeBlindPix::fgChargeNbins        = 5300;
+const Axis_t   MHCalibrationChargeBlindPix::fgChargeFirst        = -100.5;
+const Axis_t   MHCalibrationChargeBlindPix::fgChargeLast         = 5199.5;
+const Float_t  MHCalibrationChargeBlindPix::fgSinglePheCut       = 200.;
+const Float_t  MHCalibrationChargeBlindPix::fgNumSinglePheLimit  =  50.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+// - the default number for fSinglePheCut (fgSingePheCut)
+// - the default number for fNumSinglePheLimit (fgNumSinglePheLimit)
+// - the default number of bins after stripping (30)
+//
+// - the default name of the  fHGausHist ("HCalibrationChargeBlindPix")
+// - the default title of the fHGausHist ("Distribution of Summed FADC slices Blind Pixel ")
+// - the default x-axis title for fHGausHist ("Sum FADC Slices")
+// - the default y-axis title for fHGausHist ("Nr. of events")
+//
+// Initializes:
+// - all pointers to NULL
+//
+// Calls:
+// - Clear()
+//
+MHCalibrationChargeBlindPix::MHCalibrationChargeBlindPix(const char *name, const char *title)
+    :  fBlindPix(NULL), fSignal(NULL), fRawEvt(NULL), 
+       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";
+
+    SetNbins( fgChargeNbins );
+    SetFirst( fgChargeFirst );
+    SetLast ( fgChargeLast  );
+    
+    SetSinglePheCut();
+    SetNumSinglePheLimit();
+
+    SetBinsAfterStripping(30);
+
+    fHGausHist.SetName("HCalibrationChargeBlindPix");
+    fHGausHist.SetTitle("Distribution of Summed FADC slices Blind Pixel");  
+    fHGausHist.SetXTitle("Sum FADC Slices");
+    fHGausHist.SetYTitle("Nr. of events");
+
+    Clear();
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fSinglePheFit
+// - fFitLegend 
+// - fHSinglePheFADCSlices
+// - fHPedestalFADCSlices    
+// 
+MHCalibrationChargeBlindPix::~MHCalibrationChargeBlindPix()
+{
+
+  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 -999.
+// - 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    = -999.;
+  fMu0       = -999.;
+  fMu1       = -999.;
+  fSigma0    = -999.;
+  fSigma1    = -999.;
+  
+  fLambdaErr = -999.;
+  fMu0Err    = -999.;
+  fMu1Err    = -999.;
+  fSigma0Err = -999.;
+  fSigma1Err = -999.;
+
+  fLambdaCheck    = -999.;
+  fLambdaCheckErr = -999.;
+  
+  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;
+  }
+
+
+  MHCalibrationChargePix::Clear();
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+}
+  
+// --------------------------------------------------------------------------
+//
+// Gets the pointers to:
+// - MRawEvtData
+// - MExtractedSignalBlindPixel
+// 
+// Initializes:
+// - fASinglePheFADCSlices(0);
+// - fAPedestalFADCSlices(0);
+//
+// Calls:
+// - MHGausHist::InitBins()
+//
+Bool_t MHCalibrationChargeBlindPix::SetupFill(const MParList *pList) 
+{
+
+  fRawEvt = (MRawEvtData*)pList->FindObject("MRawEvtData");
+  if (!fRawEvt)
+    {
+      *fLog << err << "MRawEvtData not found... aborting." << endl;
+      return kFALSE;
+    }
+  
+  fSignal  = (MExtractedSignalBlindPixel*)pList->FindObject("MExtractedSignalBlindPixel");
+  if (!fSignal)
+    {
+      *fLog << err << "MExtractedSignalBlindPixel not found... aborting " << endl;
+      return kFALSE;
+    }
+  
+  fASinglePheFADCSlices(0);
+  fAPedestalFADCSlices(0);
+  
+  InitBins();
+  
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationChargeBlindPix
+//
+Bool_t MHCalibrationChargeBlindPix::ReInit(MParList *pList)
+{
+
+  fBlindPix = (MCalibrationChargeBlindPix*)pList->FindCreateObj("MCalibrationChargeBlindPix");
+  if (!fBlindPix)
+      return kFALSE;
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHCalibrationChargeBlindPix::Fill(const MParContainer *par, const Stat_t w)
+{
+
+  const Int_t samples = (Int_t)fRawEvt->GetNumHiGainSamples()+(Int_t)fRawEvt->GetNumLoGainSamples();
+
+  if (fASinglePheFADCSlices.GetNrows() != samples)
+    {
+      fASinglePheFADCSlices.ResizeTo(samples);
+      fAPedestalFADCSlices.ResizeTo(samples);
+    }
+
+  Float_t slices = (Float_t)fSignal->GetNumFADCSamples();
+  
+  if (slices == 0.)
+    {
+      *fLog << err << "Number of used signal slices in MExtractedSignalBlindPix is zero  ... abort." 
+            << endl;
+      return kFALSE;
+    }
+  
+  //
+  // Signal extraction and histogram filling
+  //
+  const Float_t signal = (Float_t)fSignal->GetExtractedSignal();
+  FillHistAndArray(signal);
+
+  //
+  // IN order to study the single-phe posistion, we extract the slices
+  //
+  const Int_t blindpixIdx = fSignal->GetBlindPixelIdx();
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  pixel.Jump(blindpixIdx);
+
+  if (signal > fSinglePheCut)
+      FillSinglePheFADCSlices(pixel);
+  else
+      FillPedestalFADCSlices(pixel);
+
+  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 MCalibrationChargeBlindPix
+// 
+Bool_t MHCalibrationChargeBlindPix::Finalize() 
+{
+  
+  if (IsEmpty())
+  {
+      *fLog << err << GetDescriptor() << ": My histogram has not been filled !! " << endl;
+      return kFALSE;
+  }
+
+  CreateFourierSpectrum();
+  fBlindPix->SetOscillating  ( !IsFourierSpectrumOK() );
+
+  fBlindPix->SetValid(kTRUE);
+
+  fMeanPedestal     = fSignal->GetPed();
+  fMeanPedestalErr  = fSignal->GetPedErr();
+  fSigmaPedestal    = fSignal->GetPedRms();
+  fSigmaPedestalErr = fSignal->GetPedRmsErr();
+
+  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;
+
+  FitPedestal();
+
+  if (FitSinglePhe())
+    fBlindPix->SetSinglePheFitOK();
+  else
+    fBlindPix->SetValid(kFALSE);
+
+  fBlindPix->SetLambda      (    fLambda               );
+  fBlindPix->SetLambdaVar   (    fLambdaErr*fLambdaErr );
+  fBlindPix->SetMu0         (    fMu0                  );
+  fBlindPix->SetMu0Err      (    fMu0Err               );
+  fBlindPix->SetMu1         (    fMu1                  );
+  fBlindPix->SetMu1Err      (    fMu1Err               );
+  fBlindPix->SetSigma0      (    fSigma0               );
+  fBlindPix->SetSigma0Err   (    fSigma0Err            );
+  fBlindPix->SetSigma1      (    fSigma1               );
+  fBlindPix->SetSigma1Err   (    fSigma1Err            );
+  fBlindPix->SetProb        (    fProb                 );
+
+  fBlindPix->SetLambdaCheck    ( fLambdaCheck          );
+  fBlindPix->SetLambdaCheckErr ( fLambdaCheckErr       );
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// 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.1;
+  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);
+      break;
+    case kEPoisson5:
+      fSinglePheFit = new TF1("SinglePheFit",&fPoissonKto5,rmin,rmax,6);
+      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:
+      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;
+  }
+  
+  const Double_t mu_0_guess = maximum_bin;
+  const Double_t si_0_guess = 40.;
+  const Double_t mu_1_guess = mu_0_guess + 100.;
+  const Double_t si_1_guess = si_0_guess + si_0_guess;
+  // Michele
+//  const Double_t lambda_1cat_guess = 0.5;
+  // const Double_t lambda_1dyn_guess = 0.5;
+  // const Double_t mu_1cat_guess = mu_0_guess + 50.;
+  // const Double_t mu_1dyn_guess = mu_0_guess + 20.;
+  // const Double_t si_1cat_guess = si_0_guess + si_0_guess;
+  // const Double_t si_1dyn_guess = si_0_guess;
+  // 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,fMeanPedestal,mu_1_guess,fSigmaPedestal,si_1_guess,norm);
+
+	fSinglePheFit->SetParLimits(0,0.,0.5);
+        fSinglePheFit->SetParLimits(1,
+                                    fMeanPedestal-5.*fMeanPedestalErr,
+                                    fMeanPedestal+5.*fMeanPedestalErr);
+	fSinglePheFit->SetParLimits(2,rmin,rmax);
+        fSinglePheFit->SetParLimits(3,
+                                    fSigmaPedestal-5.*fSigmaPedestalErr,
+                                    fSigmaPedestal+5.*fSigmaPedestalErr);
+	fSinglePheFit->SetParLimits(4,0.,(rmax-rmin));
+	fSinglePheFit->SetParLimits(5,norm-(0.5*norm),norm+(0.5*norm));
+	break;
+    case kEPoisson5:
+    case kEPoisson6:
+      fSinglePheFit->SetParameters(lambda_guess,mu_0_guess,mu_1_guess,si_0_guess,si_1_guess,norm);
+      fSinglePheFit->SetParNames("#lambda","#mu_{0}","#mu_{1}","#sigma_{0}","#sigma_{1}","Area");
+      fSinglePheFit->SetParLimits(0,0.,1.);
+      fSinglePheFit->SetParLimits(1,rmin,(rmax-rmin)/1.5);
+      fSinglePheFit->SetParLimits(2,(rmax-rmin)/2.,(rmax-0.05*(rmax-rmin)));
+      fSinglePheFit->SetParLimits(3,1.0,(rmax-rmin)/2.0);
+      fSinglePheFit->SetParLimits(4,1.0,(rmax-rmin)/2.5);
+      fSinglePheFit->SetParLimits(5,norm-0.1,norm+0.1);
+      break;
+
+    case kEPolya:
+        fSinglePheFit->SetParameters(lambda_guess, excessPoisson_guess,
+                                     delta1_guess,delta2_guess,
+                                     electronicAmp_guess,
+                                     fSigmaPedestal,
+                                     norm, 
+                                     fMeanPedestal);
+      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,
+                                    fSigmaPedestal-3.*fSigmaPedestalErr,
+                                    fSigmaPedestal+3.*fSigmaPedestalErr);
+      fSinglePheFit->SetParLimits(6,norm-0.1,norm+0.1);
+      fSinglePheFit->SetParLimits(7,
+                                    fMeanPedestal-3.*fMeanPedestalErr,
+                                    fMeanPedestal+3.*fMeanPedestalErr);
+      break;
+    case kEMichele:
+      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.;
+    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());
+
+  FitGaus(opt, rmin, rmax);
+
+  const Stat_t   entries = fHGausHist.Integral("width");
+  const Double_t fitarea = fFGausFit->GetParameter(0);
+  const Double_t pedarea = fitarea * TMath::Sqrt(TMath::TwoPi()) * fFGausFit->GetParameter(2);
+
+  fLambdaCheck     = TMath::Log(entries/pedarea);
+  fLambdaCheckErr  =   fFGausFit->GetParError(0)/fFGausFit->GetParameter(0)
+                     + fFGausFit->GetParError(2)/fFGausFit->GetParameter(2);
+
+  
+  SetPedestalFitOK();
+  return;
+}
+
+ 
+// -------------------------------------------------------------------------
+//
+// Draw a legend with the fit results
+//
+void MHCalibrationChargeBlindPix::DrawLegend()
+{
+
+  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=4))" :
+				(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);
+  
+  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: %4.2f ",fProb);
+  TText *t8 = fFitLegend->AddText(line8.Data());
+  t8->SetBit(kCanDelete);
+  
+  if (IsSinglePheFitOK())
+  {
+      TText *t = fFitLegend->AddText(0.,0.,"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 legend and fASinglePheFADCSlices and fAPedestalFADCSlices
+// "all": executes additionally MHGausEvents::Draw(), with option "fourierevents"
+//
+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;
+
+  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(2,2);
+      pad->cd(1);
+  }
+  else
+  {
+      pad = oldpad;
+      pad->Divide(2,2);
+      pad->cd(1);
+  }
+
+  if (!IsEmpty())
+      gPad->SetLogy();
+
+  gPad->SetTicks();
+
+  fHGausHist.Draw(opt); 
+  if (fFGausFit)
+  {
+      fFGausFit->SetLineColor(kBlue);
+      fFGausFit->Draw("same");
+  }
+  if (fSinglePheFit)
+  {    
+      fSinglePheFit->SetLineColor(IsSinglePheFitOK() ? kGreen : kRed);          
+      fSinglePheFit->Draw("same");
+  }
+
+  pad->cd(2);
+  DrawLegend();
+
+  pad->cd(3);
+  if (fHSinglePheFADCSlices)
+      delete fHSinglePheFADCSlices;
+
+  fHSinglePheFADCSlices = new TH1F(fASinglePheFADCSlices);
+  fHSinglePheFADCSlices->SetName("SinglePheFADCSlices");
+  fHSinglePheFADCSlices->SetTitle(Form("%s%f","Assumed Single Phe FADC Slices, Sum > ",fSinglePheCut));
+  fHSinglePheFADCSlices->SetXTitle("FADC slice number");
+  fHSinglePheFADCSlices->SetYTitle("FADC counts");
+  fHSinglePheFADCSlices->Draw(opt);
+
+  pad->cd(4);
+  if (fHPedestalFADCSlices)
+      delete fHPedestalFADCSlices;
+
+  fHPedestalFADCSlices = new TH1F(fAPedestalFADCSlices);
+  fHPedestalFADCSlices->SetName("PedestalFADCSlices");
+  fHPedestalFADCSlices->SetTitle(Form("%s%f","Pedestal FADC Slices, Sum < ",fSinglePheCut));
+  fHPedestalFADCSlices->SetXTitle("FADC slice number");
+  fHPedestalFADCSlices->SetYTitle("FADC counts");
+  fHPedestalFADCSlices->Draw(opt);
+
+  if (win < 2)
+  return;
+
+  oldpad->cd(2);
+  MHGausEvents::Draw("fourierevents");
+}
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeBlindPix.h	(revision 3781)
@@ -0,0 +1,507 @@
+#ifndef MARS_MHCalibrationChargeBlindPix
+#define MARS_MHCalibrationChargeBlindPix
+
+
+#ifndef MARS_MHCalibrationChargePix
+#include "MHCalibrationChargePix.h"
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.h>
+#endif
+
+#ifndef ROOT_TF1
+#include <TF1.h>
+#endif
+
+class TH1F;
+class TF1;
+class TPaveText;
+class TText;
+class MRawEvtData;
+class MRawEvtPixelIter;
+class MCalibrationChargeBlindPix;
+class MExtractedSignalBlindPixel;
+class MHCalibrationChargeBlindPix : public MHCalibrationChargePix
+{
+private:
+
+  static const Int_t    fgChargeNbins;       //! Default for fNBins        (now set to: 5300   )
+  static const Axis_t   fgChargeFirst;       //! Default for fFirst        (now set to: -100.5 )
+  static const Axis_t   fgChargeLast;        //! Default for fLast         (now set to: 5199.5 )
+  static const Float_t  fgSinglePheCut;      //! Default for fSinglePheCut (now set to: 200   )
+  static const Float_t  fgNumSinglePheLimit; //! Default for fNumSinglePheLimit (now set to: 50  )
+
+  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 
+
+  MCalibrationChargeBlindPix *fBlindPix;     //! Storage container results  
+  MExtractedSignalBlindPixel *fSignal;       //! Storage container extracted signal
+  MRawEvtData                *fRawEvt;       //! Storage container raw data
+ 
+  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
+ 
+  Double_t  fMeanPedestal;                   // Mean pedestal from pedestal run
+  Double_t  fSigmaPedestal;                  // Sigma pedestal from pedestal run
+
+  Double_t  fMeanPedestalErr;                // Error of Mean pedestal from pedestal run 
+  Double_t  fSigmaPedestalErr;               // Error of Sigma pedestal from pedestal run
+
+  Byte_t    fFlags;                          // Bit-field for the flags
+  enum { kSinglePheFitOK, kPedestalFitOK };  // Possible bits to be set
+
+  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()
+
+  // Fill histos
+  void  FillSinglePheFADCSlices(const MRawEvtPixelIter &iter);
+  void  FillPedestalFADCSlices( const MRawEvtPixelIter &iter);
+
+  // Fit
+  Bool_t InitFit();
+  void   ExitFit();  
+  
+public:
+
+  MHCalibrationChargeBlindPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeBlindPix();
+
+  void Clear(Option_t *o="");  
+
+  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();
+  
+  // Setters
+  void SetSinglePheCut      ( const Float_t cut =fgSinglePheCut      )    { fSinglePheCut      = cut;      }
+  void SetNumSinglePheLimit ( const Float_t lim =fgNumSinglePheLimit )    { fNumSinglePheLimit = lim;      }
+
+  void SetMeanPedestal      ( const Float_t f )   { fMeanPedestal     = f;  }
+  void SetMeanPedestalErr   ( const Float_t f )   { fMeanPedestalErr  = f;  }
+  void SetSigmaPedestal     ( const Float_t f )   { fSigmaPedestal    = f;  }
+  void SetSigmaPedestalErr  ( const Float_t f )   { fSigmaPedestalErr = f;  }
+
+  void SetSinglePheFitOK    ( const Bool_t b=kTRUE);
+  void SetPedestalFitOK     ( const Bool_t b=kTRUE);
+  
+  // 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;      }
+
+  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;
+  
+  // Draws
+  void Draw(Option_t *opt="");
+
+private:
+  void DrawLegend();
+  
+  // Fits
+public:
+  enum FitFunc_t  { kEPoisson4, kEPoisson5, kEPoisson6, kEPoisson7, kEPolya, kEMichele }; // The possible fit functions
+
+private:
+  FitFunc_t fFitFunc;
+
+public:
+  Bool_t FitSinglePhe (Option_t *opt="RL0+Q");
+  void   FitPedestal  (Option_t *opt="RL0+Q");
+
+  void   ChangeFitFunc(const FitFunc_t func)  { fFitFunc = func;  }
+  
+  // 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 (mu1cat    < mu0)
+        return FLT_MAX;
+
+      if (sigma1cat < sigma0)
+        return FLT_MAX;
+
+      // if (sigma1cat < sigma1dyn)
+      // return NoWay;
+
+      //if (mu1cat < mu1dyn)
+      // return NoWay;
+
+      //      if (lambda1cat < lambda1dyn)
+      // return NoWay;
+
+      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 (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 (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 (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-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.cc	(revision 3781)
@@ -0,0 +1,794 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 MHGausEvents-classes 
+// MHCalibrationChargeHiGainPix and MHCalibrationChargeLoGainPix for every:
+//
+// - Pixel, stored in the TObjArray's MHCalibrationCam::fHiGainArray and 
+//   MHCalibrationCam::fLoGainArray
+//
+// - Average pixel per AREA index (e.g. inner and outer for the MAGIC camera), 
+//   stored in the TObjArray's MHCalibrationCam::fAverageHiGainAreas and 
+//   MHCalibrationCam::fAverageLoGainAreas
+//
+// - Average pixel per camera SECTOR (e.g. sectors 1-6 for the MAGIC camera), 
+//   stored in the TObjArray'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 
+// +- MHGausEvents::fPickupLimit (default: 5) sigma (see MHGausEvents::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHGausEvents::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 MHGausEvents::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHGausEvents::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 "MHCalibrationChargeHiGainPix.h"
+#include "MHCalibrationChargeLoGainPix.h"
+#include "MHCalibrationChargePix.h"
+
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MHGausEvents.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+#include "MRawEvtData.h"
+#include "MRawEvtPixelIter.h"
+
+#include "MExtractedSignalCam.h"
+#include "MExtractedSignalPix.h"
+
+ClassImp(MHCalibrationChargeCam);
+
+using namespace std;
+
+const Float_t MHCalibrationChargeCam::fgNumHiGainSaturationLimit = 0.01;
+const Float_t MHCalibrationChargeCam::fgNumLoGainSaturationLimit = 0.005;
+const Float_t MHCalibrationChargeCam::fgTimeLowerLimit           = 1.;
+const Float_t MHCalibrationChargeCam::fgTimeUpperLimit           = 2.;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets:
+// - all pointers to NULL
+//
+// Initializes:
+// - fNumHiGainSaturationLimit to fgNumHiGainSaturationLimit
+// - fNumLoGainSaturationLimit to fgNumLoGainSaturationLimit
+// - fTimeLowerLimit           to fgTimeLowerLimit 
+// - fTimeUpperLimit           to fgTimeUpperLimit 
+//
+MHCalibrationChargeCam::MHCalibrationChargeCam(const char *name, const char *title)
+    : fRawEvt(NULL)
+{
+  fName  = name  ? name  : "MHCalibrationChargeCam";
+  fTitle = title ? title : "Class to fill the calibration histograms ";
+  
+  SetNumHiGainSaturationLimit();
+  SetNumLoGainSaturationLimit();
+  SetTimeLowerLimit();
+  SetTimeUpperLimit();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+// - MBadPixelsCam
+//
+// Initializes the number of used FADC slices from MExtractedSignalCam 
+// into MCalibrationChargeCam and test for changes in that variable
+//
+// 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::InitHists() for every entry in:
+// - MHCalibrationCam::fHiGainArray, MHCalibrationCam::fLoGainArray
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+// Sets Titles and Names for the Charge Histograms:
+// - MHCalibrationCam::fAverageHiGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors
+// 
+// Sets number of bins to MHCalibrationCam::fAverageNbins for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+// 
+Bool_t MHCalibrationChargeCam::ReInitHists(MParList *pList)
+{
+
+  MExtractedSignalCam *signal = (MExtractedSignalCam*)pList->FindObject("MExtractedSignalCam");
+  if (!signal)
+  {
+      *fLog << err << "MExtractedSignalCam not found... abort." << endl;
+      return kFALSE;
+  }
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationChargeCam");
+  if (!fCam)
+    {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationChargeCam"));
+      if (!fCam)
+        {
+          gLog << err << "Cannot find nor create MCalibrationChargeCam ... abort." << endl;
+          return kFALSE;
+        }
+      else 
+        fCam->Init(*fGeom);
+    }
+
+  fFirstHiGain = signal->GetFirstUsedSliceHiGain();
+  fLastHiGain  = signal->GetLastUsedSliceHiGain();
+  fFirstLoGain = signal->GetFirstUsedSliceLoGain();
+  fLastLoGain  = signal->GetLastUsedSliceLoGain();
+
+  const Float_t numhigain = signal->GetNumUsedHiGainFADCSlices();
+  const Float_t numlogain = signal->GetNumUsedLoGainFADCSlices();  
+
+  if (fCam->GetNumHiGainFADCSlices() == 0.)
+    fCam->SetNumHiGainFADCSlices ( numhigain );
+  else if (fCam->GetNumHiGainFADCSlices() != numhigain)
+    {
+      *fLog << err << GetDescriptor() 
+            << ": Number of High Gain FADC extraction slices has changed, abort..." << endl;
+      return kFALSE;
+    }
+
+  if (fCam->GetNumLoGainFADCSlices() == 0.)
+    fCam->SetNumLoGainFADCSlices ( numlogain );
+  else if (fCam->GetNumLoGainFADCSlices() != numlogain)
+    {
+      *fLog << err << GetDescriptor() 
+            << ": Number of Low Gain FADC extraction slices has changes, abort..." << endl;
+      return kFALSE;
+    }
+
+  const Int_t npixels  = fGeom->GetNumPixels();
+  const Int_t nsectors = fGeom->GetNumSectors();
+  const Int_t nareas   = fGeom->GetNumAreas();
+
+  if (fHiGainArray->GetEntries()==0)
+  {
+      fHiGainArray->Expand(npixels);
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fHiGainArray)[i] = new MHCalibrationChargeHiGainPix;
+          InitHists((*this)[i],(*fBadPixels)[i],i);
+      }
+  }
+
+  if (fLoGainArray->GetEntries()==0)
+  {
+      fLoGainArray->Expand(npixels);
+      
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fLoGainArray)[i] = new MHCalibrationChargeLoGainPix;
+          InitHists((*this)(i),(*fBadPixels)[i],i);
+      }
+      
+  }
+
+  if (fAverageHiGainAreas->GetEntries()==0)
+  {
+    fAverageHiGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageHiGainAreas)[j] = 
+          new MHCalibrationChargeHiGainPix("AverageHiGainArea",
+                                           "Average HiGain FADC sums area idx ");
+
+        InitHists(GetAverageHiGainArea(j),fCam->GetAverageBadArea(j),j);
+
+        MHCalibrationChargePix &hist = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+
+        hist.GetHGausHist()->SetTitle("Summed FADC slices average HiGain Area Idx ");
+        hist.SetNbins(fAverageNbins);
+        hist.GetHAbsTime()->SetTitle("Absolute Arrival Time average HiGain Area Idx ");
+      }
+  }
+
+
+  if (fAverageLoGainAreas->GetEntries()==0)
+    {
+      fAverageLoGainAreas->Expand(nareas);
+      
+      for (Int_t j=0; j<nareas; j++)
+        {
+	  (*fAverageLoGainAreas)[j] = 
+            new MHCalibrationChargeLoGainPix("AverageLoGainArea",
+                                             "Average LoGain FADC sums of pixel area idx ");
+
+        MHCalibrationChargePix &hist = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+
+        InitHists(hist,fCam->GetAverageBadArea(j),j);
+
+        hist.GetHGausHist()->SetTitle("Summed FADC slices average LoGain Area Idx ");
+        hist.SetNbins(fAverageNbins);
+        hist.GetHAbsTime()->SetTitle("Absolute Arrival Time average LoGain Area Idx ");
+
+        }
+    }
+  
+  if (fAverageHiGainSectors->GetEntries()==0)
+  {
+      fAverageHiGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageHiGainSectors)[j] = 
+            new MHCalibrationChargeHiGainPix("AverageHiGainSector",
+                                             "Average HiGain FADC sums of pixel sector ");
+
+          MHCalibrationChargePix &hist = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+
+          InitHists(hist,fCam->GetAverageBadSector(j),j);
+          
+          hist.GetHGausHist()->SetTitle("Summed FADC slices average HiGain Sector ");
+          hist.SetNbins(fAverageNbins);
+          hist.GetHAbsTime()->SetTitle("Absolute Arrival Time average HiGain Sector ");
+
+      }
+  }
+
+  if (fAverageLoGainSectors->GetEntries()==0)
+  {
+      fAverageLoGainSectors->Expand(nsectors);
+  
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageLoGainSectors)[j] = 
+            new MHCalibrationChargeLoGainPix("AverageLoGainSector",
+                                             "Average LoGain FADC sums of pixel sector ");
+
+          MHCalibrationChargePix &hist = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+
+          InitHists(hist,fCam->GetAverageBadSector(j),j);
+          
+          hist.GetHGausHist()->SetTitle("Summed FADC slices average LoGain Sector ");
+          hist.SetNbins(fAverageNbins);
+          hist.GetHAbsTime()->SetTitle("Absolute Arrival Time average LoGain Sector ");
+
+      }
+  }
+
+  return kTRUE;
+}
+
+  
+// --------------------------------------------------------------------------
+//
+// Retrieves from MExtractedSignalCam:
+// - first used LoGain FADC slice
+//
+// Retrieves from MGeomCam:
+// - number of pixels
+// - number of pixel areas
+// - number of sectors
+//
+// For all TObjArray'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::SetSaturated()) 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();
+
+  Float_t sumhiarea  [nareas],   sumloarea  [nareas],   timehiarea  [nareas],   timeloarea  [nareas];
+  Float_t sumhisector[nsectors], sumlosector[nsectors], timehisector[nsectors], timelosector[nsectors];
+  Int_t   sathiarea  [nareas],   satloarea  [nareas];
+  Int_t   sathisector[nsectors], satlosector[nsectors];
+
+  memset(sumhiarea,   0, nareas * sizeof(Float_t));
+  memset(sumloarea,   0, nareas * sizeof(Float_t));
+  memset(timehiarea,  0, nareas * sizeof(Float_t));
+  memset(timeloarea,  0, nareas * sizeof(Float_t));
+  memset(sathiarea,   0, nareas * sizeof(Int_t  ));
+  memset(satloarea,   0, nareas * sizeof(Int_t  ));
+  memset(sumhisector, 0, nsectors*sizeof(Float_t));
+  memset(sumlosector, 0, nsectors*sizeof(Float_t));
+  memset(timehisector,0, nsectors*sizeof(Float_t));
+  memset(timelosector,0, nsectors*sizeof(Float_t));
+  memset(sathisector, 0, nsectors*sizeof(Int_t  ));
+  memset(satlosector, 0, nsectors*sizeof(Int_t  ));
+
+  for (UInt_t i=0; i<npixels; i++)
+    {
+
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const MExtractedSignalPix &pix = (*signal)[i];
+      
+      const Float_t sumhi  = pix.GetExtractedSignalHiGain();
+      const Float_t sumlo  = pix.GetExtractedSignalLoGain();
+      
+      histhi.FillHistAndArray(sumhi);
+      histlo.FillHistAndArray(sumlo);
+
+      const Int_t sathi = (Int_t)pix.GetNumHiGainSaturated();
+      const Int_t satlo = (Int_t)pix.GetNumLoGainSaturated();
+
+      histhi.SetSaturated(sathi); 
+      histlo.SetSaturated(satlo); 
+
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      sumhiarea[aidx]  += sumhi;
+      sumloarea[aidx]  += sumlo;
+      sathiarea[aidx]  += sathi;
+      satloarea[aidx]  += satlo;
+
+      sumhisector[sector]  += sumhi;
+      sumlosector[sector]  += sumlo;
+      sathisector[sector]  += sathi;
+      satlosector[sector]  += satlo;
+    }
+
+  MRawEvtPixelIter pixel(fRawEvt);
+  while (pixel.Next())
+    {
+      
+      const UInt_t pixid = pixel.GetPixelId();
+
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[pixid];
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(pixid);
+
+      if (histhi.IsExcluded())
+         continue;
+      
+      const Float_t timehi = (Float_t)pixel.GetIdxMaxHiGainSample();
+      const Float_t timelo = (Float_t)pixel.GetIdxMaxLoGainSample(lofirst);
+
+      histhi.FillAbsTime(timehi);
+      histlo.FillAbsTime(timelo);
+
+      const Int_t aidx   = (*fGeom)[pixid].GetAidx();
+      const Int_t sector = (*fGeom)[pixid].GetSector();
+
+      timehiarea[aidx] += timehi;
+      timeloarea[aidx] += timelo;
+
+      timehisector[sector] += timehi;
+      timelosector[sector] += timelo;
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+
+      const Int_t npix = fAverageAreaNum[j];
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainArea(j);
+      MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainArea(j);
+
+      hipix.FillHistAndArray(sumhiarea[j]/npix);
+      lopix.FillHistAndArray(sumloarea[j]/npix);
+
+      hipix.SetSaturated((Float_t)sathiarea[j]/npix); 
+      lopix.SetSaturated((Float_t)satloarea[j]/npix); 
+
+      hipix.FillAbsTime(timehiarea[j]/npix);
+      lopix.FillAbsTime(timeloarea[j]/npix);
+
+    }
+
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+
+      const Int_t npix = fAverageSectorNum[j];
+
+      MHCalibrationChargePix &hipix = (MHCalibrationChargePix&)GetAverageHiGainSector(j);
+      MHCalibrationChargePix &lopix = (MHCalibrationChargePix&)GetAverageLoGainSector(j);
+
+      hipix.FillHistAndArray(sumhisector[j]/npix);
+      lopix.FillHistAndArray(sumlosector[j]/npix);
+
+      hipix.SetSaturated((Float_t)sathisector[j]/npix); 
+      lopix.SetSaturated((Float_t)satlosector[j]/npix); 
+
+      hipix.FillAbsTime(timehisector[j]/npix);
+      lopix.FillAbsTime(timelosector[j]/npix);
+
+    }
+
+  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 MHCalibrationChargeCam::FinalizeHists()
+{
+
+  for (Int_t i=0; i<fHiGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)(*this)[i];
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)(*fCam)[i];
+      MBadPixelsPix          &bad    = (*fBadPixels)[i];
+      
+      if (histhi.IsExcluded())
+        continue;
+      
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+    }
+
+  for (Int_t i=0; i<fLoGainArray->GetSize(); i++)
+    {
+      
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)(*this)(i);
+      MBadPixelsPix          &bad    = (*fBadPixels)[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 ); 
+          histlo.CreateFourierSpectrum();
+          continue;
+        }
+  
+      MCalibrationChargePix &pix    = (MCalibrationChargePix&)(*fCam)[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&)fCam->GetAverageArea(j);
+      MBadPixelsPix          &bad    = fCam->GetAverageBadArea(j);
+      
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+   }
+  
+  for (Int_t j=0; j<fAverageLoGainAreas->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainArea(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)fCam->GetAverageArea(j);
+      MBadPixelsPix          &bad    = fCam->GetAverageBadArea(j);      
+
+      if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn << "Saturated Lo Gain histogram in area idx: " << j << endl;
+          histlo.CreateFourierSpectrum();
+          continue;
+        }
+
+      if (pix.IsHiGainSaturation())
+        FinalizeAbsTimes(histlo, pix, bad, fFirstLoGain, fLastLoGain);
+    }
+
+  for (Int_t j=0; j<fAverageHiGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histhi = (MHCalibrationChargePix&)GetAverageHiGainSector(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)fCam->GetAverageSector(j);
+      MBadPixelsPix          &bad    = fCam->GetAverageBadSector(j);      
+
+      if (histhi.GetSaturated() > fNumHiGainSaturationLimit*histhi.GetHGausHist()->GetEntries())
+        {
+          pix.SetHiGainSaturation();
+          histhi.CreateFourierSpectrum();
+          continue;
+        }
+
+      FinalizeAbsTimes(histhi, pix, bad, fFirstHiGain, fLastHiGain);
+    }
+  
+  for (Int_t j=0; j<fAverageLoGainSectors->GetSize(); j++)
+    {
+      
+      MHCalibrationChargePix &histlo = (MHCalibrationChargePix&)GetAverageLoGainSector(j);      
+      MCalibrationChargePix  &pix    = (MCalibrationChargePix&)fCam->GetAverageSector(j);
+      MBadPixelsPix          &bad    = fCam->GetAverageBadSector(j);        
+      
+      if (histlo.GetSaturated() > fNumLoGainSaturationLimit*histlo.GetHGausHist()->GetEntries())
+        {
+          *fLog << warn << "Saturated Lo Gain histogram in sector: " << j << endl;
+          bad.SetUncalibrated( MBadPixelsPix::kLoGainSaturation ); 
+          histlo.CreateFourierSpectrum();
+          continue;
+        }
+
+      if (pix.IsHiGainSaturation())
+        FinalizeAbsTimes(histlo, pix, bad, fFirstLoGain, fLastLoGain);
+    }
+  
+  //
+  // Perform the fitting for the High Gain (done in MHCalibrationCam)
+  //
+  FitHiGainArrays((MCalibrationCam&)(*fCam),(*fBadPixels),
+                  MBadPixelsPix::kHiGainNotFitted,
+                  MBadPixelsPix::kHiGainOscillating);
+  //
+  // Perform the fitting for the Low Gain (done in MHCalibrationCam)
+  //
+  FitLoGainArrays((MCalibrationCam&)(*fCam),(*fBadPixels),
+                  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 << GetDescriptor() 
+            << Form("%s%3.1f%s%2.1f%s%4i",": Mean ArrivalTime: ",mean," smaller than ",fTimeLowerLimit,
+                    " FADC slices from lower edge in pixel ",hist.GetPixId()) << endl;
+      bad.SetUncalibrated( MBadPixelsPix::kMeanTimeInFirstBin );
+    }
+  
+  if ( mean  > upperlimit )
+    {
+      *fLog << warn << GetDescriptor() 
+            << Form("%s%3.1f%s%2.1f%s%4i",": Mean ArrivalTime: ",mean," greater than ",fTimeUpperLimit,
+                    " FADC slices from upper edge in pixel ",hist.GetPixId()) << 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()
+{
+      
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      
+      MBadPixelsPix    &bad    = (*fBadPixels)[i];
+      MCalibrationPix  &pix    = (*fCam)[i];
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiGainNotFitted ))
+        if (!pix.IsHiGainSaturation())
+          bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+ 
+      if (bad.IsUncalibrated( MBadPixelsPix::kHiGainOscillating ))
+        bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kLoGainNotFitted ))
+        if (pix.IsHiGainSaturation())
+          bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+ 
+      if (bad.IsUncalibrated( MBadPixelsPix::kLoGainOscillating ))
+        if (pix.IsHiGainSaturation())
+          bad.SetUnsuitable(   MBadPixelsPix::kUnreliableRun    );
+
+      if (bad.IsUncalibrated( MBadPixelsPix::kLoGainSaturation ))
+          bad.SetUnsuitable(   MBadPixelsPix::kUnsuitableRun    );
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// Dummy, needed by MCamEvent
+//
+Bool_t MHCalibrationChargeCam::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::DrawClone() for pixel idx
+//
+void MHCalibrationChargeCam::DrawPixelContent(Int_t idx) const
+{
+  (*this)[idx].DrawClone();
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeCam.h	(revision 3781)
@@ -0,0 +1,70 @@
+#ifndef MARS_MHCalibrationChargeCam
+#define MARS_MHCalibrationChargeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MRawEvtData;
+class MExtractedSignalCam;
+class MCalibrationChargePix;
+class MHCalibrationChargePix;
+class MHCalibrationChargeCam : public MHCalibrationCam
+{
+private:
+
+  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.)
+  
+  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
+  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   FinalizeAbsTimes (MHCalibrationChargePix &hist, MCalibrationChargePix &pix, MBadPixelsPix &bad,
+                           Byte_t first, Byte_t last);  
+  Bool_t FinalizeHists();
+  void   FinalizeBadPixels();
+
+
+ public:
+
+  MHCalibrationChargeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeCam() {}
+  
+  void SetNumLoGainSaturationLimit( const Float_t lim=fgNumLoGainSaturationLimit) { fNumLoGainSaturationLimit = lim; }
+  void SetNumHiGainSaturationLimit( const Float_t lim=fgNumHiGainSaturationLimit) { fNumHiGainSaturationLimit = lim; }
+  void SetTimeLowerLimit    ( const Float_t f=fgTimeLowerLimit         ) { fTimeLowerLimit    = f;   }
+  void SetTimeUpperLimit    ( const Float_t f=fgTimeUpperLimit         ) { fTimeUpperLimit    = f;   }
+  
+  Float_t GetNumHiGainSaturationLimit()      const  { return fNumHiGainSaturationLimit; }
+  Float_t GetNumLoGainSaturationLimit()      const  { return fNumLoGainSaturationLimit; }
+
+  Bool_t GetPixelContent ( Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void   DrawPixelContent( Int_t num )  const;    
+
+  ClassDef(MHCalibrationChargeCam, 1)	// Histogram class for Charge Camera Calibration 
+};
+
+#endif
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.cc	(revision 3781)
@@ -0,0 +1,85 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargeHiGainPix
+//
+//  Histogram class for the charge High Gain FADC calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Charges are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeHiGainPix.h"
+
+#include <TH1.h>
+
+ClassImp(MHCalibrationChargeHiGainPix);
+
+using namespace std;
+
+const Int_t   MHCalibrationChargeHiGainPix::fgChargeNbins     = 2000;
+const Axis_t  MHCalibrationChargeHiGainPix::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationChargeHiGainPix::fgChargeLast      = 1999.5;
+const Int_t   MHCalibrationChargeHiGainPix::fgAbsTimeNbins    = 20;
+const Axis_t  MHCalibrationChargeHiGainPix::fgAbsTimeFirst    = -0.5;
+const Axis_t  MHCalibrationChargeHiGainPix::fgAbsTimeLast     = 19.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+// - the default number for fAbsTimeNbins (fgAbstTimeNbins)
+// - the default number for fAbsTimeFirst (fgAbsTimeFirst)
+// - the default number for fAbsTimeLast  (fgAbsTimeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationChargeHiGainPix")
+// - the default title of the fHGausHist ("Distribution of Summed Hi Gain FADC slices Pixel ")
+//
+// - the default name of the  fHAbsTime ("HAbsTimeHiGainPix")
+// - the default title of the fHAbsTime ("Distribution of Absolute Arrival Times Hi Gain Pixel ")
+//
+MHCalibrationChargeHiGainPix::MHCalibrationChargeHiGainPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeHiGainPix";
+  fTitle = title ? title : "Fill the FADC sums of the HiGainPix events and perform the fits Pixel ";
+  
+  SetNbins ( fgChargeNbins );
+  SetFirst ( fgChargeFirst );
+  SetLast  ( fgChargeLast  );
+  
+  SetAbsTimeNbins();
+  SetAbsTimeFirst();
+  SetAbsTimeLast();
+
+  fHGausHist.SetName ("HCalibrationChargeHiGainPix");
+  fHGausHist.SetTitle("Distribution of Summed Hi Gain FADC slices Pixel ");  
+
+  fHAbsTime.SetName ("HAbsTimeHiGainPix");
+  fHAbsTime.SetTitle("Distribution of Absolute Arrival Times Hi Gain Pixel ");  
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeHiGainPix.h	(revision 3781)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHCalibrationChargeHiGainPix
+#define MARS_MHCalibrationChargeHiGainPix
+
+
+#ifndef MARS_MHCalibrationChargePix
+#include "MHCalibrationChargePix.h"
+#endif
+
+class TH1F;
+class MHCalibrationChargeHiGainPix : public MHCalibrationChargePix
+{
+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)
+  static const Int_t   fgAbsTimeNbins;    // Default for fAbsTimeNbins (now set to: 20    )
+  static const Axis_t  fgAbsTimeFirst;    // Default for fAbsTimeFirst (now set to: -0.5  )
+  static const Axis_t  fgAbsTimeLast;     // Default for fAbsTimeLast  (now set to: 19.5  )
+
+public:
+
+  MHCalibrationChargeHiGainPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeHiGainPix(){}
+
+  // 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;    }
+
+  ClassDef(MHCalibrationChargeHiGainPix, 1)  // Histogram class for Charge High Gain Pixel Calibration 
+};
+
+#endif
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.cc	(revision 3781)
@@ -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 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationChargeLoGainPix
+//
+//  Histogram class for the charge Low Gain FADC calibration. 
+//  Stores and fits the charges and stores the location of the maximum FADC 
+//  slice. Charges are taken from MExtractedSignalPix.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationChargeLoGainPix.h"
+
+#include <TH1.h>
+
+ClassImp(MHCalibrationChargeLoGainPix);
+
+using namespace std;
+
+const Int_t   MHCalibrationChargeLoGainPix::fgChargeNbins     = 200;
+const Axis_t  MHCalibrationChargeLoGainPix::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationChargeLoGainPix::fgChargeLast      = 199.5;
+const Int_t   MHCalibrationChargeLoGainPix::fgAbsTimeNbins    = 15;
+const Axis_t  MHCalibrationChargeLoGainPix::fgAbsTimeFirst    = -0.5;
+const Axis_t  MHCalibrationChargeLoGainPix::fgAbsTimeLast     = 14.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+// - the default number for fAbsTimeNbins (fgAbstTimeNbins)
+// - the default number for fAbsTimeFirst (fgAbsTimeFirst)
+// - the default number for fAbsTimeLast  (fgAbsTimeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationChargeLoGainPix")
+// - the default title of the fHGausHist ("Distribution of Summed Lo Gain FADC slices Pixel ")
+//
+// - the default name of the  fHAbsTime ("HAbsTimeLoGainPix")
+// - the default title of the fHAbsTime ("Distribution of Absolute Arrival Times Lo Gain Pixel ")
+//
+MHCalibrationChargeLoGainPix::MHCalibrationChargeLoGainPix(const char *name, const char *title)
+{
+
+  fName  = name  ? name  : "MHCalibrationChargeLoGainPix";
+  fTitle = title ? title : "Fill the FADC sums of the Low Gain events and perform the fits Pixel ";
+  
+  SetNbins ( fgChargeNbins );
+  SetFirst ( fgChargeFirst );
+  SetLast  ( fgChargeLast  );
+  
+  SetAbsTimeNbins();
+  SetAbsTimeFirst();
+  SetAbsTimeLast();
+
+  fHGausHist.SetName ("HCalibrationChargeLoGainPix");
+  fHGausHist.SetTitle("Distribution of Summed Lo Gain FADC slices Pixel ");  
+
+  fHAbsTime.SetName ("HAbsTimeLoGainPix");
+  fHAbsTime.SetTitle("Distribution of Absolute Arrival Times Lo Gain Pixel ");  
+}
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargeLoGainPix.h	(revision 3781)
@@ -0,0 +1,41 @@
+#ifndef MARS_MHCalibrationChargeLoGainPix
+#define MARS_MHCalibrationChargeLoGainPix
+
+
+#ifndef MARS_MHCalibrationChargePix
+#include "MHCalibrationChargePix.h"
+#endif
+
+class MHCalibrationChargeLoGainPix : public MHCalibrationChargePix
+{
+private:
+
+  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   fgAbsTimeNbins;     // Default for fAbsTimeNbins (now set to: 15    )
+  static const Axis_t  fgAbsTimeFirst;     // Default for fAbsTimeFirst (now set to: -0.5  )
+  static const Axis_t  fgAbsTimeLast;      // Default for fAbsTimeLast  (now set to: 14.5  )
+
+public:
+
+  MHCalibrationChargeLoGainPix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargeLoGainPix(){}
+
+  // 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;    }
+
+  ClassDef(MHCalibrationChargeLoGainPix, 1)  // Histogram class for Charge Low Gain Pixel Calibration
+};
+
+#endif
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.cc	(revision 3781)
@@ -0,0 +1,396 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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      = 199.5;
+const Int_t   MHCalibrationChargePINDiode::fgChargeNbins     = 200;
+const Int_t   MHCalibrationChargePINDiode::fgRmsChargeNbins  = 100;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeFirst  = 0.;
+const Axis_t  MHCalibrationChargePINDiode::fgRmsChargeLast   = 100.;  
+const Float_t MHCalibrationChargePINDiode::fgTimeLowerLimit  = 3.;
+const Float_t MHCalibrationChargePINDiode::fgTimeUpperLimit  = 4.;
+// --------------------------------------------------------------------------
+//
+// 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)
+//
+// 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();
+
+  fHGausHist.SetName("HCalibrationChargePINDiode");
+  fHGausHist.SetTitle("Distribution of Summed FADC slices PIN Diode");  
+  fHGausHist.SetXTitle("Sum FADC Slices");
+  fHGausHist.SetYTitle("Nr. of events");
+
+  fHAbsTime.SetName("HAbsTimePINDiode");
+  fHAbsTime.SetTitle("Distribution of Absolute Arrival Times PIN Diode");  
+  fHAbsTime.SetXTitle("Absolute Arrival Time [FADC slice nr]");
+  fHAbsTime.SetYTitle("Nr. of events");
+
+  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) 
+{
+
+  MHGausEvents::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)
+  {
+      *fLog << err << "MExtractedSignalPINDiode not found... aborting " << endl;
+      return kFALSE;
+  }
+
+  fPINDiode = (MCalibrationChargePINDiode*)pList->FindCreateObj("MCalibrationChargePINDiode");
+  if (!fPINDiode)
+  {
+      *fLog << err << "MCalibrationChargePINDiode not found... aborting " << endl;
+      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 MHGausEvents::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;
+
+  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);
+  MHGausEvents::Draw("fourierevents");
+}
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePINDiode.h	(revision 3781)
@@ -0,0 +1,84 @@
+#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.)
+  
+  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;     }
+
+  ClassDef(MHCalibrationChargePINDiode, 1)  // Histogram class for Charge PIN Diode Calibration 
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.cc	(revision 3781)
@@ -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): 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;
+
+const Int_t   MHCalibrationChargePix::fgChargeNbins     = 2000;
+const Axis_t  MHCalibrationChargePix::fgChargeFirst     = -0.5;
+const Axis_t  MHCalibrationChargePix::fgChargeLast      = 1999.5;
+const Int_t   MHCalibrationChargePix::fgAbsTimeNbins    = 15;
+const Axis_t  MHCalibrationChargePix::fgAbsTimeFirst    = -0.5;
+const Axis_t  MHCalibrationChargePix::fgAbsTimeLast     = 14.5;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins        (fgChargeNbins)
+// - the default number for fFirst        (fgChargeFirst)
+// - the default number for fLast         (fgChargeLast)
+// - the default number for fAbsTimeNbins (fgAbsTimeNbins)
+// - the default number for fAbsTimeFirst (fgAbsTimeFirst)
+// - the default number for fAbsTimeLast  (fgAbsTimeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationCharge")
+// - the default title of the fHGausHist ("Distribution of Summed FADC slices Pixel ")
+// - 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 ("HAbsTimePixel")
+// - the default title of the fHAbsTime ("Distribution of Absolute Arrival Times Pixel ")
+// - 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()
+{ 
+  
+  fName  = name  ? name  : "MHCalibrationChargePix";
+  fTitle = title ? title : "Statistics of the FADC sums of calibration events";
+
+  SetNbins ( fgChargeNbins );
+  SetFirst ( fgChargeFirst );
+  SetLast  ( fgChargeLast  );
+
+  SetAbsTimeNbins();
+  SetAbsTimeFirst();
+  SetAbsTimeLast();
+
+  fHGausHist.SetName("HCalibrationCharge");
+  fHGausHist.SetTitle("Distribution of Summed FADC slices Pixel");  
+  fHGausHist.SetXTitle("Sum FADC Slices");
+  fHGausHist.SetYTitle("Nr. of events");
+
+  fHAbsTime.SetName("HAbsTimePixel");
+  fHAbsTime.SetTitle("Distribution of Absolute Arrival Times Pixel ");  
+  fHAbsTime.SetXTitle("Absolute Arrival Time [FADC slice nr]");
+  fHAbsTime.SetYTitle("Nr. of 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets:
+// - fSaturated to 0.
+// 
+// Executes:
+// - MHGausEvents::Clear()
+//
+void MHCalibrationChargePix::Clear(Option_t *o)
+{
+
+  fSaturated = 0.;
+
+  MHGausEvents::Clear();
+  return;
+}
+
+// --------------------------------------------------------------------------
+//
+// Empty function to overload MHGausEvents::Reset()
+//
+void MHCalibrationChargePix::Reset()
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::ChangeHistId()
+//
+// Add id to names and titles of: 
+// - fHAbsTime
+//
+void MHCalibrationChargePix::ChangeHistId(Int_t id)
+{
+
+  MHGausEvents::ChangeHistId(id);
+
+  fHAbsTime.SetName (Form("%s%d", fHAbsTime.GetName(),  id));
+  fHAbsTime.SetTitle(Form("%s%d", fHAbsTime.GetTitle(), id));
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHGausEvents::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
+  {
+      pad = oldpad;
+      pad->Divide(1,2);
+      pad->cd(1);
+  }
+
+  if (!IsEmpty())
+      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(opt); 
+  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(opt);
+
+  if (win < 2)
+      return;
+
+  oldpad->cd(2);
+  MHGausEvents::Draw("fourierevents");
+
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationChargePix.h	(revision 3781)
@@ -0,0 +1,68 @@
+#ifndef MARS_MHCalibrationChargePix
+#define MARS_MHCalibrationChargePix
+
+#ifndef MARS_MHGausEvents
+#include "MHGausEvents.h"
+#endif
+
+class TH1F;
+class MHCalibrationChargePix : public MHGausEvents
+{
+
+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)
+  static const Int_t   fgAbsTimeNbins;       // Default for fAbsTimeNbins   (now set to: 15    )
+  static const Axis_t  fgAbsTimeFirst;       // Default for fAbsTimeFirst   (now set to: -0.5  )
+  static const Axis_t  fgAbsTimeLast;        // Default for fAbsTimeLast    (now set to: 14.5  )
+
+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
+
+  Float_t  fSaturated;     // Number of events classified as saturated
+
+public:
+
+  MHCalibrationChargePix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationChargePix() {}
+
+  virtual void Clear(Option_t *o="");
+  virtual void Reset();  
+  virtual void InitBins();
+  
+  // Setters 
+  virtual void SetAbsTimeNbins(const Int_t  bins =fgAbsTimeNbins)  { fAbsTimeNbins = bins;  }
+  virtual void SetAbsTimeFirst(const Axis_t first=fgAbsTimeFirst)  { fAbsTimeFirst = first; }
+  virtual void SetAbsTimeLast( const Axis_t last =fgAbsTimeLast)   { fAbsTimeLast  = last;  }
+
+  void SetSaturated          ( const Float_t f    )                { fSaturated += f;      }
+
+  // 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;
+  const Float_t  GetSaturated()         const { return fSaturated;   }
+
+  // Fill histos
+  Bool_t FillAbsTime(const Float_t t);
+
+  // Draws
+  virtual void Draw(Option_t *opt="");
+
+  // Miscelleaneous
+  void ChangeHistId(Int_t id);
+  
+  ClassDef(MHCalibrationChargePix, 1)     // Base Histogram class for Charge Pixel Calibration
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.cc	(revision 3781)
@@ -0,0 +1,485 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 MHGausEvents-classes MHCalibrationRelTimePix 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 
+// +- MHGausEvents::fPickupLimit (default: 5) sigma (see MHGausEvents::RepeatFit())
+// In case this does not make the fit valid, the histogram means and RMS's are 
+// taken directly (see MHGausEvents::BypassFit()) and the following flags are set:
+// - MBadPixelsPix::SetUncalibrated( MBadPixelsPix::kRelTimeNotFitted ) and
+// - MBadPixelsPix::SetUnsuitable(   MBadPixelsPix::kUnreliableRun    ) 
+// 
+// Outliers of more than MHGausEvents::fPickupLimit (default: 5) sigmas 
+// from the mean are counted as Pickup events (stored in MHGausEvents::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 "MHCalibrationRelTimePix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MCalibrationRelTimeCam.h"
+#include "MCalibrationPix.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimePix.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MBadPixelsCam.h"
+#include "MBadPixelsPix.h"
+
+ClassImp(MHCalibrationRelTimeCam);
+
+using namespace std;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+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";
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Gets or creates the pointers to:
+// - MCalibrationRelTimeCam
+//
+// Searches pointer to:
+// - MArrivalTimeCam
+//
+// 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::InitHists() 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
+// 
+// Sets number of bins to MHCalibrationCam::fAverageNbins for:
+// - MHCalibrationCam::fAverageHiGainAreas, MHCalibrationCam::fAverageLoGainAreas
+// - MHCalibrationCam::fAverageHiGainSectors, MHCalibrationCam::fAverageLoGainSectors
+//
+Bool_t MHCalibrationRelTimeCam::ReInitHists(MParList *pList)
+{
+
+  fCam = (MCalibrationCam*)pList->FindObject("MCalibrationRelTimeCam");
+  if (!fCam)
+    {
+      fCam = (MCalibrationCam*)pList->FindCreateObj(AddSerialNumber("MCalibrationRelTimeCam"));
+      if (!fCam)
+        {
+          gLog << err << "Cannot find nor create MCalibrationRelTimeCam ... abort." << endl;
+          return kFALSE;
+        }
+      else 
+        fCam->Init(*fGeom);
+    }
+  
+  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();
+
+  if (fHiGainArray->GetEntries()==0)
+  {
+      fHiGainArray->Expand(npixels);
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fHiGainArray)[i] = new MHCalibrationRelTimePix("MHCalibrationRelTimePixHiGain",
+                                                          "Relative Arrival Time High Gain Pixel");
+          InitHists((*this)[i],(*fBadPixels)[i],i);
+      }
+  }
+
+  if (fLoGainArray->GetEntries()==0)
+  {
+      fLoGainArray->Expand(npixels);
+      for (Int_t i=0; i<npixels; i++)
+      {
+	  (*fLoGainArray)[i] = new MHCalibrationRelTimePix("MHCalibrationRelTimePixLoGain",
+                                                          "Relative Arrival Time Low Gain Pixel");
+          InitHists((*this)(i),(*fBadPixels)[i],i);
+      }
+  }
+
+  if (fAverageHiGainAreas->GetEntries()==0)
+  {
+    fAverageHiGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageHiGainAreas)[j] = 
+          new MHCalibrationRelTimePix("MHCalibrationRelTimeAverageAreaHiGain",
+                                      "Average Relative Arrival Times High Gain Area Idx ");
+
+        GetAverageHiGainArea(j).GetHGausHist()->SetTitle("Relative Arrival Times HiGain Area Idx ");
+        GetAverageHiGainArea(j).SetNbins(fAverageNbins);
+
+        InitHists(GetAverageHiGainArea(j),fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageLoGainAreas->GetEntries()==0)
+  {
+    fAverageLoGainAreas->Expand(nareas);
+    
+    for (Int_t j=0; j<nareas; j++)
+      {
+        (*fAverageLoGainAreas)[j] = 
+          new MHCalibrationRelTimePix("MHCalibrationRelTimeAverageAreaLoGain",
+                                      "Average Relative Arrival Times Low Gain Area Idx ");
+
+        GetAverageLoGainArea(j).GetHGausHist()->SetTitle("Relative Arrival Times LoGain Area Idx ");
+        GetAverageLoGainArea(j).SetNbins(fAverageNbins);
+
+        InitHists(GetAverageLoGainArea(j),fCam->GetAverageBadArea(j),j);
+      }
+  }
+
+  if (fAverageHiGainSectors->GetEntries()==0)
+  {
+      fAverageHiGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageHiGainSectors)[j] = 
+            new MHCalibrationRelTimePix("MHCalibrationRelTimeAverageSectorHiGain",
+                                        "Average Relative Arrival Times High Gain Sector ");
+
+          GetAverageHiGainSector(j).GetHGausHist()->SetTitle("Relative Arrival Times HiGain Sector ");
+          GetAverageHiGainSector(j).SetNbins(fAverageNbins);
+
+          InitHists(GetAverageHiGainSector(j),fCam->GetAverageBadSector(j),j);
+      }
+  }
+
+  if (fAverageLoGainSectors->GetEntries()==0)
+  {
+      fAverageLoGainSectors->Expand(nsectors);
+
+      for (Int_t j=0; j<nsectors; j++)
+      {
+	  (*fAverageLoGainSectors)[j] = 
+            new MHCalibrationRelTimePix("MHCalibrationRelTimeAverageSectorLoGain",
+                                        "Average Relative Arrival Times Low Gain Sector ");
+
+          GetAverageLoGainSector(j).GetHGausHist()->SetTitle("Relative Arrival Times LoGain Sector ");
+          GetAverageLoGainSector(j).SetNbins(fAverageNbins);
+
+          InitHists(GetAverageLoGainSector(j),fCam->GetAverageBadSector(j),j);
+          
+      }
+  }
+
+  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 UInt_t npixels  = fGeom->GetNumPixels();
+  const UInt_t nareas   = fGeom->GetNumAreas();
+  const UInt_t nsectors = fGeom->GetNumSectors();
+
+  Float_t sumareahi  [nareas],   sumarealo  [nareas];
+  Float_t sumsectorhi[nsectors], sumsectorlo[nsectors];
+  Int_t   numareahi  [nareas],   numarealo  [nareas];
+  Int_t   numsectorhi[nsectors], numsectorlo[nsectors];
+
+  memset(sumareahi,   0, nareas * sizeof(Float_t));
+  memset(sumarealo,   0, nareas * sizeof(Float_t));
+  memset(sumsectorhi, 0, nsectors*sizeof(Float_t));
+  memset(sumsectorlo, 0, nsectors*sizeof(Float_t));
+  
+  const MArrivalTimePix &refpix = (*arrtime)[1];
+  const Float_t reftime = refpix.IsLoGainUsed() 
+    ? refpix.GetArrivalTimeLoGain() : refpix.GetArrivalTimeHiGain();
+
+  for (Int_t i=0; i<npixels; i++)
+    {
+
+      MHGausEvents &histhi = (*this)[i];
+      MHGausEvents &histlo = (*this)(i);
+
+      if (histhi.IsExcluded())
+	continue;
+
+      const MArrivalTimePix &pix = (*arrtime)[i];
+      const Float_t time    = pix.IsLoGainUsed() 
+        ? pix.GetArrivalTimeLoGain() : pix.GetArrivalTimeHiGain();  
+      const Float_t reltime = time - reftime;
+      
+      const Int_t aidx   = (*fGeom)[i].GetAidx();
+      const Int_t sector = (*fGeom)[i].GetSector();
+
+      if (pix.IsLoGainUsed())
+        { 
+          histlo.FillHistAndArray(reltime);
+          sumarealo  [aidx]   += reltime;
+          numarealo  [aidx]   ++;
+          sumsectorlo[sector] += reltime;
+          numsectorlo[sector] ++;
+        }
+      else
+        {
+          histhi.FillHistAndArray(reltime) ;
+          sumareahi  [aidx]   += reltime;
+          numareahi  [aidx]   ++;
+          sumsectorhi[sector] += reltime;
+          numsectorhi[sector] ++;
+        }
+    }
+  
+  for (UInt_t j=0; j<nareas; j++)
+    {
+      MHGausEvents &histhi = GetAverageHiGainArea(j);
+      histhi.FillHistAndArray(numareahi[j] == 0 ? 0. : sumareahi[j]/numareahi[j]);
+
+      MHGausEvents &histlo = GetAverageLoGainArea(j);
+      histlo.FillHistAndArray(numarealo[j] == 0 ? 0. : sumarealo[j]/numarealo[j]);
+    }
+  
+  for (UInt_t j=0; j<nsectors; j++)
+    {
+      MHGausEvents &histhi = GetAverageHiGainSector(j);
+      histhi.FillHistAndArray(numsectorhi[j] == 0 ? 0. : sumsectorhi[j]/numsectorhi[j]);
+
+      MHGausEvents &histlo = GetAverageLoGainSector(j);
+      histlo.FillHistAndArray(numsectorlo[j] == 0 ? 0. : sumsectorlo[j]/numsectorlo[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()
+{
+
+  FitHiGainArrays((*fCam),*fBadPixels,
+                  MBadPixelsPix::kRelTimeNotFitted,
+                  MBadPixelsPix::kRelTimeOscillating);
+
+  FitLoGainArrays((*fCam),*fBadPixels,
+                  MBadPixelsPix::kRelTimeNotFitted,
+                  MBadPixelsPix::kRelTimeOscillating);
+
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Sets all pixels to MBadPixelsPix::kUnreliableRun, if following flags are set:
+// - MBadPixelsPix::kRelTimeNotFitted
+// - MBadPixelsPix::kRelTimeOscillating
+//
+void MHCalibrationRelTimeCam::FinalizeBadPixels()
+{
+
+  for (Int_t i=0; i<fBadPixels->GetSize(); i++)
+    {
+      
+      MBadPixelsPix          &bad    = (*fBadPixels)[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              (calls: MHGausEvents::GetMean())
+// 1: Error of fitted Mean Relative Arrival Time     (calls: MHGausEvents::GetMeanErr())
+// 2: Sigma of fitted Relative Arrival Time          (calls: MHGausEvents::GetSigma())
+// 3: Error of Sigma of fitted Relative Arrival Time (calls: 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;
+
+  switch (type)
+    {
+    case 0:
+      val = (*this)[idx].GetMean();
+      break;
+    case 1:
+      val = (*this)[idx].GetMeanErr();
+      break;
+    case 2:
+      val = (*this)[idx].GetSigma();
+      break;
+    case 3:
+      val = (*this)[idx].GetSigmaErr();
+      break;
+    case 4:
+      val = (*this)[idx].GetProb();
+      break;
+    case 5:
+      if (!(*this)[idx].IsGausFitOK())
+        val = 1.;
+      break;
+    case 6:
+      if (!(*this)[idx].IsFourierSpectrumOK())
+        val = 1.;
+      break;
+    default:
+      return kFALSE;
+    }
+  return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calls MHGausEvents::DrawClone() for pixel idx
+//
+void MHCalibrationRelTimeCam::DrawPixelContent(Int_t idx) const
+{
+ (*this)[idx].DrawClone();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimeCam.h	(revision 3781)
@@ -0,0 +1,31 @@
+#ifndef MARS_MHCalibrationRelTimeCam
+#define MARS_MHCalibrationRelTimeCam
+
+#ifndef MARS_MHCalibrationCam
+#include "MHCalibrationCam.h"
+#endif
+
+class MGeomCam;
+class MHCalibrationRelTimeCam : public MHCalibrationCam
+{
+
+private:
+
+  Bool_t ReInitHists(MParList *pList);
+  Bool_t FillHists(const MParContainer *par, const Stat_t w=1);
+  Bool_t FinalizeHists();
+  void    FinalizeBadPixels();
+  
+public:
+
+  MHCalibrationRelTimeCam(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationRelTimeCam() {}
+
+  Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const;
+  void DrawPixelContent(Int_t idx) const;
+  
+  ClassDef(MHCalibrationRelTimeCam, 1)	// Histogram class for Relative Time Camera Calibration
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.cc	(revision 3781)
@@ -0,0 +1,119 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHCalibrationRelTimePix
+//
+//  Histogram class for the relative arrival time calibration. 
+//  Stores and fits the relative arrival times between pixel fPixId and 
+//  pixel number 1 (hardware index: 2). Times are taken from MArrivalTimePix
+//
+//  Results are re-normalized to a value per time (ns) with the formulae:
+//
+// - Mean Rel. Time         = Mean Rel. Time        * fFADCSliceWidth
+// - Mean Rel. Time Error   = Mean Rel. Time Error  * fFADCSliceWidth
+// - Sigma Rel. Time        = Sigma Rel. Time       * fFADCSliceWidth
+// - Sigma Rel. Time Error  = Sigma Rel. Time Error * fFADCSliceWidth
+// 
+//////////////////////////////////////////////////////////////////////////////
+#include "MHCalibrationRelTimePix.h"
+
+#include <TH1.h>
+
+ClassImp(MHCalibrationRelTimePix);
+
+using namespace std;
+//
+const Int_t   MHCalibrationRelTimePix::fgRelTimeNbins    = 900;
+const Axis_t  MHCalibrationRelTimePix::fgRelTimeFirst    = -13.;
+const Axis_t  MHCalibrationRelTimePix::fgRelTimeLast     =  13.;
+const Float_t MHCalibrationRelTimePix::fgFADCSliceWidth  =  3.3333;
+// --------------------------------------------------------------------------
+//
+// Default Constructor. 
+//
+// Sets: 
+// - the default number for fNbins  (fgRelTimeNbins)
+// - the default number for fFirst  (fgRelTimeFirst)
+// - the default number for fLast   (fgRelTimeLast)
+//
+// - the default name of the  fHGausHist ("HCalibrationRelTime")
+// - the default title of the fHGausHist ("Distribution of Relative Arrival Times Pixel ")
+// - the default x-axis title for fHGausHist ("FADC Slice")
+// - the default y-axis title for fHGausHist ("Nr. of events")
+// 
+// - the default number for fFADCSliceWidth (fgFADCSliceWidth)
+//
+MHCalibrationRelTimePix::MHCalibrationRelTimePix(const char *name, const char *title) 
+{ 
+
+  fName  = name  ? name  : "MHCalibrationRelTimePix";
+  fTitle = title ? title : "Histogrammed Calibration Relative Arrival Time events";
+
+  SetNbins ( fgRelTimeNbins );
+  SetFirst ( fgRelTimeFirst );
+  SetLast  ( fgRelTimeLast  );
+  SetFADCSliceWidth();
+
+  // Create a large number of bins, later we will rebin
+  fHGausHist.SetName("HCalibrationRelTime");
+  fHGausHist.SetTitle("Distribution of Relative Arrival Times Pixel ");
+  fHGausHist.SetXTitle("FADC Slice");
+  fHGausHist.SetYTitle("Nr. of events");
+
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Empty function to overload MHGausEvents::Reset()
+//
+void MHCalibrationRelTimePix::Reset()
+{
+}
+
+// --------------------------------------------------------------------------
+// 
+// If mean and sigma have not yet been set, returns.
+//
+// Results are re-normalized to a value per time (ns) with the formulae:
+//
+// - Mean Rel. Time         = Mean Rel. Time        * fFADCSliceWidth
+// - Mean Rel. Time Error   = Mean Rel. Time Error  * fFADCSliceWidth
+// - Sigma Rel. Time        = Sigma Rel. Time       * fFADCSliceWidth
+// - Sigma Rel. Time Error  = Sigma Rel. Time Error * fFADCSliceWidth
+// 
+void MHCalibrationRelTimePix::Renorm()
+{
+
+  if (fMean == fMeanErr == fSigma == fSigmaErr == 0.)
+    return;
+
+  fMean    *= fFADCSliceWidth;
+  fMeanErr *= fFADCSliceWidth;
+  fSigma   *= fFADCSliceWidth;
+  fSigmaErr*= fFADCSliceWidth;
+  
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHCalibrationRelTimePix.h	(revision 3781)
@@ -0,0 +1,34 @@
+#ifndef MARS_MHCalibrationRelTimePix
+#define MARS_MHCalibrationRelTimePix
+
+#ifndef MARS_MHGausEvents
+#include "MHGausEvents.h"
+#endif
+
+class MHCalibrationRelTimePix : public MHGausEvents
+{
+
+private:
+
+  static const Int_t   fgRelTimeNbins;      //! Default for fNbins          (now set to: 900   )
+  static const Axis_t  fgRelTimeFirst;      //! Default for fFirst          (now set to: -13.5 )
+  static const Axis_t  fgRelTimeLast;       //! Default for fLast           (now set to:  13.5 )
+  static const Float_t fgFADCSliceWidth;    //! Default for fFADCSliceWidth (now set to: 3.333)
+  
+  Float_t fFADCSliceWidth;                  //  Time FADC Slice Width in ns.
+  
+public:
+
+  MHCalibrationRelTimePix(const char *name=NULL, const char *title=NULL);
+  ~MHCalibrationRelTimePix() {}
+
+  // Setters
+  void SetFADCSliceWidth( const Float_t f=fgFADCSliceWidth )  {  fFADCSliceWidth = f; }
+  
+  void Reset();
+  void Renorm();
+  
+  ClassDef(MHCalibrationRelTimePix, 1)     // Histogram class for Relative Time Pixel Calibration
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.cc	(revision 3781)
@@ -0,0 +1,992 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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()
+//     - One can completely skip the fitting to set mean, sigma and its errors directly 
+//       from the histograms with the function BypassFit()
+// 
+//  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 "MFFT.h"
+#include "MArray.h"
+
+#include "MH.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHGausEvents);
+
+using namespace std;
+
+const Int_t    MHGausEvents::fgBinsAfterStripping   = 40;
+const Float_t  MHGausEvents::fgBlackoutLimit        = 5.;
+const Int_t    MHGausEvents::fgNDFLimit             = 2;
+const Float_t  MHGausEvents::fgPickupLimit          = 5.;
+const Float_t  MHGausEvents::fgProbLimit            = 0.001;
+const Int_t    MHGausEvents::fgPowerProbabilityBins = 20;
+// --------------------------------------------------------------------------
+//
+// 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 for fPickupLimit           (fgPickupLimit)
+// - the default number for fBlackoutLimit         (fgBlackoutLimit)
+// - 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), fHPowerProbability(NULL), 
+      fPowerSpectrum(NULL),
+      fGraphEvents(NULL), fGraphPowerSpectrum(NULL),
+      fEvents(0), fFGausFit(NULL), fFExpFit(NULL),
+      fFirst(0.), fHGausHist(), fLast(100.), 
+      fNbins(100), fPixId(-1)
+{ 
+
+  fName  = name  ? name  : "MHGausEvents";
+  fTitle = title ? title : "Events with expected Gaussian distributions";
+
+  Clear();
+  
+  SetBinsAfterStripping();
+  SetBlackoutLimit();
+  SetNDFLimit();
+  SetPickupLimit();
+  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);
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// Default Destructor. 
+//
+// Deletes (if Pointer is not NULL):
+// 
+// - fHPowerProbability
+// - fFGausFit 
+// - fFExpFit
+// - fPowerSpectrum     
+// - fGraphEvents
+// - fGraphPowerSpectrum
+// 
+MHGausEvents::~MHGausEvents()
+{
+
+  // delete histograms
+  if (fHPowerProbability)
+    delete fHPowerProbability;
+  
+  // delete fits
+  if (fFGausFit)
+    delete fFGausFit; 
+  if (fFExpFit)
+    delete fFExpFit;
+  
+  // 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., except fPixId to -1 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;
+  fPixId             = -1;
+
+  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;
+    }
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// 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 MHGausEvents::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: " << fPixId << endl;
+      return;
+    }
+  
+  fMean     = fHGausHist.GetMean();
+  fMeanErr  = fHGausHist.GetRMS() / TMath::Sqrt(entries);
+  fSigma    = fHGausHist.GetRMS() ;
+  fSigmaErr = fHGausHist.GetRMS() / TMath::Sqrt(entries) / 2.;
+}
+
+
+
+// --------------------------------------------------------------------------
+//
+// - Set fPixId to id
+//
+// Add id to names and titles of:
+// - fHGausHist
+//
+void MHGausEvents::ChangeHistId(const Int_t id)
+{
+
+  fPixId = id;
+
+  fHGausHist.SetName(  Form("%s%d", fHGausHist.GetName(),  id));
+  fHGausHist.SetTitle( Form("%s%d", fHGausHist.GetTitle(), id));
+
+  fName  = Form("%s%d", fName.Data(),  id);
+  fTitle = Form("%s%d", fTitle.Data(), id);
+
+}
+
+// -----------------------------------------------------------------------------
+// 
+// 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 pixel: " << fPixId 
+            << ". 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
+  MArray::StripZeros(fEvents);
+
+  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,
+                                    "PowerProbability",
+                                    "Probability of Power occurrance");
+  fHPowerProbability->SetXTitle("P(f)");
+  fHPowerProbability->SetDirectory(NULL);
+  //
+  // 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;
+
+  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()
+{
+
+  MArray::StripZeros(fEvents);
+
+  const Int_t n = fEvents.GetSize();
+
+  fGraphEvents = new TGraph(n,CreateEventXaxis(n),fEvents.GetArray());  
+  fGraphEvents->SetTitle("Evolution of Events with time");
+  fGraphEvents->GetXaxis()->SetTitle((fEventFrequency) ? "Time [s]" : "Event Nr.");
+}
+
+// ----------------------------------------------------------------------------------
+//
+// 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()
+{
+
+  MArray::StripZeros(*fPowerSpectrum);
+
+  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)");
+}
+
+
+// -----------------------------------------------------------------------------
+// 
+// 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, 900);
+
+  TString option(opt);
+  option.ToLower();
+  
+  Int_t win = 1;
+
+  if (option.Contains("events"))
+    {
+      option.ReplaceAll("events","");
+      win += 1;
+    }
+  if (option.Contains("fourier"))
+    {
+      option.ReplaceAll("fourier","");
+      win += 2;
+    }
+  
+  pad->SetTicks();
+  pad->SetBorderMode(0);
+  pad->Divide(1,win);
+  pad->cd(1);
+
+  if (!IsEmpty())
+    gPad->SetLogy();
+
+  fHGausHist.Draw(opt);
+
+  if (fFGausFit)
+    {
+      fFGausFit->SetLineColor(IsGausFitOK() ? kGreen : kRed);
+      fFGausFit->Draw("same");
+    }
+  switch (win)
+    {
+    case 2:
+      pad->cd(2);
+      DrawEvents();
+      break;
+    case 3:
+      pad->cd(2);
+      DrawPowerSpectrum(*pad,3);
+      break;
+    case 4:
+      pad->cd(2);
+      DrawEvents();
+      pad->cd(3);
+      DrawPowerSpectrum(*pad,4);
+      break;
+    }
+}
+
+void MHGausEvents::DrawEvents()
+{
+  
+  if (!fGraphEvents)
+    CreateGraphEvents();
+
+  fGraphEvents->SetBit(kCanDelete);
+  fGraphEvents->SetTitle("Events with time");
+  fGraphEvents->Draw("AL");
+  
+}
+
+
+void MHGausEvents::DrawPowerSpectrum(TVirtualPad &pad, Int_t i)
+{
+  
+  if (fPowerSpectrum)
+    {
+      if (!fGraphPowerSpectrum)
+        CreateGraphPowerSpectrum();
+      
+      fGraphPowerSpectrum->Draw("AL");          
+      fGraphPowerSpectrum->SetBit(kCanDelete);
+    }
+  
+  pad.cd(i);
+
+  if (fHPowerProbability && fHPowerProbability->GetEntries() > 0)
+    {
+      gPad->SetLogy();
+      fHPowerProbability->Draw();
+      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 about fBinsAfterStripping bins. 
+  //
+  // (ATTENTION: The Chisquare method is more sensitive, 
+  // the _less_ bins, you have!)
+  //
+  StripZeros(&fHGausHist,fBinsAfterStripping);
+  
+  //
+  // Get the fitting ranges
+  //
+  Axis_t rmin = (xmin==0.) && (xmax==0.) ? fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetFirst()) : xmin;
+  Axis_t rmax = (xmin==0.) && (xmax==0.) ? fHGausHist.GetBinCenter(fHGausHist.GetXaxis()->GetLast())  : xmax;
+
+  //
+  // First guesses for the fit (should be as close to reality as possible, 
+  //
+  const Stat_t   entries     = fHGausHist.Integral("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 pixel: " << fPixId << endl;
+    return kFALSE;
+    }
+  
+  fFGausFit->SetParameters(area_guess,mu_guess,sigma_guess);
+  fFGausFit->SetParNames("Area","#mu","#sigma");
+  fFGausFit->SetParLimits(0,0.,area_guess*1.5);
+  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;
+}
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "blackout" events, which are events with values higher 
+// than fBlackoutLimit sigmas from the mean
+//
+//
+const Double_t MHGausEvents::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, "width");
+}
+
+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.);
+}
+
+
+// -------------------------------------------------------------------------------
+//
+// Return the number of "pickup" events, which are events with values higher 
+// than fPickupLimit sigmas from the mean
+//
+//
+const Double_t MHGausEvents::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, "width");
+}
+
+
+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()
+{
+  fHGausHist.SetBins(fNbins,fFirst,fLast);
+}
+
+const Bool_t MHGausEvents::IsEmpty() const
+{
+    return !(fHGausHist.GetEntries());
+}
+
+
+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 pixel: " << fPixId     << 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;
+  
+}
+
+// --------------------------------------------------------------------------
+//
+// Re-normalize the results, has to be overloaded
+//
+void  MHGausEvents::Renorm()
+{
+}
+
+// -----------------------------------------------------------------------------
+//
+// 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 MHGausEvents::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);
+  fMeanErr  = fFGausFit->GetParameter(2);
+  fSigma    = 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;
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Default Reset(), can be overloaded.
+//
+// Executes:
+// - Clear()
+// - fHGausHist.Reset()
+// - fEvents.Set(0)
+//
+void MHGausEvents::Reset()
+{
+
+  Clear();
+  fHGausHist.Reset();
+  fEvents.Set(0);
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MHGausEvents.h	(revision 3781)
@@ -0,0 +1,169 @@
+#ifndef MARS_MHGausEvents
+#define MARS_MHGausEvents
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TVirtualPad;
+class TGraph;
+class TArrayF;
+class TH1F;
+class TH1I;
+class TF1;
+class MHGausEvents : public MH
+{
+private:
+
+  const static Int_t    fgBinsAfterStripping;   //! Default for fBinsAfterStripping   (now set to: 40)
+  const static Float_t  fgBlackoutLimit;        //! Default for fBlackoutLimit        (now set to: 5. )
+  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 Float_t  fgPickupLimit;          //! Default for fPickupLimit          (now set to: 5. )
+  const static Int_t    fgPowerProbabilityBins; //! Default for fPowerProbabilityBins (now set to: 20)
+  
+  Int_t    fBinsAfterStripping;        // Bins for the Gauss Histogram after stripping off the zeros at both ends
+  Int_t    fCurrentSize;               // Current size of the array fEvents
+  Float_t  fEventFrequency;            // Event frequency in Hertz (to be set)
+  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
+  TArrayF *fPowerSpectrum;             // Fourier transform of fEvents
+  TGraph  *fGraphEvents;               //! TGraph to display the event array (will not be cloned!!)
+  TGraph  *fGraphPowerSpectrum;        //! TGraph to display the power spectrum array (will not be cloned!!)
+
+  enum { kGausFitOK, kExpFitOK, kFourierSpectrumOK, kExcluded }; // Bits for information about fit results 
+  
+protected:
+
+  Float_t  fBlackoutLimit;             // Lower number sigmas from mean until event is considered blackout
+  TArrayF  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()) 
+  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
+  Float_t  fPickupLimit;               // Upper number sigmas from mean until event is considered pickup
+  Int_t    fPixId;                     // Pixel ID 
+  Double_t fProb;                      // Probability of the Gauss fit 
+  Float_t  fProbLimit;                 // Probability limit for judgement if fit is OK 
+
+  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
+
+  void DrawEvents();                                  // Draw graph of fEvents
+  void DrawPowerSpectrum(TVirtualPad &pad, Int_t i);  // Draw graph of fPowerSpectrum and fHPowerProbability
+
+  // Setters
+  void  SetPowerProbabilityBins ( const Int_t nbins=fgPowerProbabilityBins ) { fPowerProbabilityBins=nbins; }
+  void  SetBinsAfterStripping   ( const Int_t nbins=fgBinsAfterStripping   ) { fBinsAfterStripping  =nbins; }
+
+ public:
+
+  MHGausEvents(const char* name=NULL, const char* title=NULL);
+  ~MHGausEvents();
+
+  virtual void Clear(Option_t *o="");
+  virtual void Reset();  
+  virtual void InitBins();
+  
+  // Setters
+  void  SetBlackoutLimit    ( const Float_t  lim=fgBlackoutLimit ) { fBlackoutLimit  = lim; }
+  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  SetPickupLimit      ( const Float_t  lim=fgPickupLimit   ) { fPickupLimit    = lim; }
+  void  SetPixId            ( const Int_t    i                   ) { fPixId          = i;   }
+  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;   }
+
+  // Getters
+  const Double_t GetBlackout()           const;  
+  const Double_t GetChiSquare()          const;
+  const Double_t GetExpChiSquare()       const;
+  const Int_t    GetExpNdf()             const;
+  const Double_t GetExpProb()            const;
+        TArrayF *GetEvents()                   { return &fEvents;            }  
+  const TArrayF *GetEvents()             const { return &fEvents;            }
+        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 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 GetMean()               const { return fMean;               }
+  const Double_t GetMeanErr()            const { return fMeanErr;            }
+  const Int_t    GetNdf()                const;
+  const Double_t GetOffset()             const;
+  const Double_t GetPickup()             const;
+  const Int_t    GetPixId()              const { return fPixId;              }
+        TArrayF *GetPowerSpectrum()            { return fPowerSpectrum;      }  
+  const TArrayF *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; 
+
+  // Fill
+  void   FillArray       ( const Float_t f );     // Fill only the array fEvents 
+  Bool_t FillHist        ( const Float_t f );     // Fill only the histogram HGausHist 
+  Bool_t FillHistAndArray( const Float_t f );     // Fill bothe the array fEvents and the histogram HGausHist
+  
+  // Fits
+  Bool_t FitGaus(  Option_t *option="RQ0",
+                   const Double_t xmin=0., 
+	           const Double_t xmax=0.);       // Fit the histogram HGausHist with a Gaussian
+  Bool_t RepeatFit(const Option_t *option="RQ0"); // Repeat fit within limits defined by fPickupLimit
+  void BypassFit();                               // Take mean and RMS from the histogram
+  
+  // Draws
+  virtual void Draw(Option_t *option="");         // Default Draw 
+  
+  // Prints
+  virtual void Print(const Option_t *o="") const; // Default Print
+  
+  // Miscelleaneous
+  virtual void ChangeHistId(const Int_t id);      // Changes names and titles of the histogram
+  virtual void Renorm();                          // Re-normalize the results 
+  
+  void CreateFourierSpectrum();                   // Create the fourier spectrum out of fEvents
+  void CreateGraphEvents();                       // Create the TGraph fGraphEvents of fEvents 
+  void CreateGraphPowerSpectrum();                // Create the TGraph fGraphPowerSpectrum out of fPowerSpectrum
+  
+  ClassDef(MHGausEvents, 1) // Base class for events with Gaussian distributed values
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.cc	(revision 3781)
@@ -0,0 +1,291 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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:
+//   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 "MHillas.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";
+
+    fHistRatio = new TH1F(AddSerialNumber("HistRatio"), "log10(fPhotElfromShower/fSize)", 1500, -3., 3.);
+    fHistRatio->SetXTitle("log_{10}(fPhotElfromShower / fSize) [photel/ADC count]");
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    fHistRatio->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;
+    }
+
+    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;
+      }
+  }
+
+  return kTRUE;
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Obtain average ratio of photons in camera to image Size.
+//
+Int_t MMcCalibrationCalc::Process()
+{
+    //
+    // Exclude events with some saturated pixel
+    //
+    if (fNew->GetNumSaturatedPixels()>0)
+        return kTRUE;
+
+    //
+    // Exclude events with low Size (larger fluctuations)
+    // FIXME? The present cut (1000 "inner-pixel-counts") is somehow
+    // arbitrary. Might it be optimized?
+    //   
+
+    const Float_t size = fHillas->GetSize(); 
+    // Size will at this point be in ADC counts (still uncalibrated)
+
+    if (size < 1000)
+        return kTRUE;
+
+    fPhot2PhotEl += (Float_t) fMcEvt->GetPhotElfromShower() /
+      (Float_t) fMcEvt->GetPassPhotCone();
+
+    fHistRatio->Fill(TMath::Log10(fMcEvt->GetPhotElfromShower()/size));
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill the MCalibrationCam object
+//
+Int_t MMcCalibrationCalc::PostProcess()
+{
+    const Stat_t n = fHistRatio->GetEntries();
+    if (n<1)
+    {
+        *fLog << err << "No events read... aborting." << endl;
+        return kFALSE;
+    }
+
+    fPhot2PhotEl /= n;   // 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 <= fHistRatio->GetNbinsX()-reach; ibin++)
+    {
+        const Stat_t sum = fHistRatio->Integral(ibin-reach, ibin+reach);
+
+        if (sum <= summax)
+            continue;
+
+        summax = sum;
+        mode = ibin;
+    }
+
+    fADC2PhotEl = TMath::Power(10, fHistRatio->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];
+
+	qepix.SetAverageQE(fPhot2PhotEl);
+
+	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 AvNormFFacto 
+	// must be 1.
+
+	
+	Float_t factor = fADC2PhotEl;
+
+	//
+	// We take into account the (possibly) different gain of outer pixels:
+	//
+	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-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/MMcCalibrationCalc.h	(revision 3781)
@@ -0,0 +1,49 @@
+#ifndef MARS_MMcCalibrationCalc
+#define MARS_MMcCalibrationCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MCalibrationChargeCam;
+class MCalibrationQECam;
+class MGeomCam;
+class MHillas;
+class MNewImagePar;
+class MMcEvt;
+class MMcFadcHeader;
+
+class TH1F;
+
+class MMcCalibrationCalc : public MTask
+{
+private:
+    MCalibrationChargeCam     *fCalCam;
+    MCalibrationQECam         *fQECam;    
+    MGeomCam                  *fGeom;
+    MHillas                   *fHillas;
+    MNewImagePar              *fNew;
+    MMcEvt                    *fMcEvt;
+    MMcFadcHeader             *fHeaderFadc;
+
+    Float_t fADC2PhotEl;   // Conversion factor (photel / ADC count)
+    Float_t fPhot2PhotEl;  // Conversion factor (photons / photoelectron) = average QE
+    Long_t  fEvents;
+
+    TH1F*   fHistRatio; // Histogram 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*   GetHist() { return fHistRatio; }
+
+    ClassDef(MMcCalibrationCalc, 0)   // Task which obtains, for MC files, the calibration factor from ADC counts to photons. 
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcalib/Makefile	(revision 3781)
@@ -0,0 +1,81 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Calib
+
+#
+# Library name to creatre
+#
+LIB   = mcalib.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgui -I../mgeom -I../manalysis \
+	   -I../mraw -I../mtools -I../mmc -I../mimage -I../msignal -I../mbadpixels
+
+# 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
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MCalibrate.cc \
+	   MCalibrateData.cc \
+	   MCalibrateRelTimes.cc \
+           MCalibrationCam.cc \
+           MCalibrationPix.cc  \
+           MCalibrationRelTimeCam.cc \
+           MCalibrationRelTimePix.cc  \
+           MCalibrationQECam.cc \
+           MCalibrationQEPix.cc  \
+           MCalibrationPedCam.cc \
+	   MCalibrationChargeCalc.cc \
+           MCalibrationChargeCam.cc \
+           MCalibrationChargePix.cc  \
+           MCalibrationChargeBlindPix.cc  \
+           MCalibrationChargePINDiode.cc  \
+           MHCalibrationChargeBlindPix.cc \
+           MHCalibrationChargeBlindPix.cc \
+           MHCalibrationChargePix.cc \
+           MHCalibrationCam.cc \
+           MHCalibrationChargeCam.cc \
+           MHCalibrationChargeHiGainPix.cc \
+           MHCalibrationChargeLoGainPix.cc \
+           MHCalibrationChargePINDiode.cc \
+           MHCalibrationRelTimeCam.cc \
+           MHCalibrationRelTimePix.cc \
+	   MMcCalibrationCalc.cc \
+	   MHGausEvents.cc 
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/CameraLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraAUX.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraAUX.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraAUX.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraAUX.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraAUX.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraAUX.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCalibration.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraCooling.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCooling.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCooling.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraCooling.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCooling.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraCooling.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraDC.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraDC.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraDC.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraDC.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraDC.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraDC.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraHV.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraHV.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraHV.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraHV.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraHV.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraHV.h	(revision 3781)
@@ -0,0 +1,60 @@
+#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;
+    }
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MCameraHV, 1) // Container storing information about the Camera HV
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLV.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLV.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLV.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraLV.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLV.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLV.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraLid.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLid.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLid.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraLid.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLid.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLid.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraLids.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLids.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLids.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraLids.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLids.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraLids.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/MCameraPowerSupply.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mcamera/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mcamera/Makefile	(revision 3781)
@@ -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  = Camera
+
+#
+# Library name to creatre
+#
+LIB   = mcamera.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui
+# mgui - MCameraDC <MCamEvent>
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MCameraAUX.cc \
+	   MCameraCalibration.cc\
+	   MCameraCooling.cc \
+	   MCameraHV.cc \
+	   MCameraLV.cc \
+	   MCameraDC.cc \
+	   MCameraLid.cc \
+	   MCameraLids.cc \
+	   MCameraPowerSupply.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataIncl.h	(revision 3781)
@@ -0,0 +1,10 @@
+#ifndef __CINT__
+
+//#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include <TGListBox.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/DataLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MData.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MData.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataArray.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataArray.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataArray.cc	(revision 3781)
@@ -0,0 +1,214 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//   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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    TIter Next(&fList);
+    MData *data = NULL;
+    while ((data=(MData*)Next()))
+    {
+        *fLog << all << " Line " << setw(3) << 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-8-4/MagicSoft/Mars/mdata/MDataArray.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataArray.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataArray.h	(revision 3781)
@@ -0,0 +1,63 @@
+#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);
+
+    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-8-4/MagicSoft/Mars/mdata/MDataChain.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataChain.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataChain.cc	(revision 3781)
@@ -0,0 +1,730 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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 brackets:
+//   "HillasDource.fDist / (MHillas.fLength + MHillas.fWidth)"
+//
+//
+// Operators
+// ---------
+//
+// The allowed operations are: +, -, *, /, %, ^
+//
+// While a%b returns the floating point reminder of a/b.
+// While a^b returns a to the power of b
+//
+// Warning: There is no priority rule build in. So better use brackets
+//   to get correct results. The rule is parsed/evaluated from the left
+//   to the right, which means:
+//
+//   "MHillas.fWidth + MHillas.fLength / HillasSource.fDist"
+//
+//    is parses as
+//
+//   "(MHillas.fWidth + MHillas.fLength) / HillasSource.fDist"
+//
+// 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 brackets to the rule it would be possible
+//    to implement priorities for operators.
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MDataChain.h"
+
+#include <ctype.h>        // isalnum, ...
+#include <stdlib.h>       // strtod, ...
+
+#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, 1);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 << "Trying to resolve rule... " << flush;
+    if (!(fMember=ParseString(rule, 1)))
+    {
+        *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());
+    TMethodCall call(TMath::Class(), name, "");
+    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());
+}
+
+// --------------------------------------------------------------------------
+//
+// Core of the data chain. Here the chain is constructed out of the rule.
+//
+MData *MDataChain::ParseString(TString txt, Int_t level)
+{
+    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 bracket
+                //
+                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 symbol '";
+                *fLog << txt[0] << "' 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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataChain.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataChain.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataChain.h	(revision 3781)
@@ -0,0 +1,71 @@
+#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);
+
+    MData *ParseString(TString txt, Int_t level);
+    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();
+
+    Double_t GetValue() const;
+    Bool_t PreProcess(const MParList *plist);
+
+    Bool_t IsValid() const { return fMember ? kTRUE : kFALSE; }
+    Bool_t IsReadyToSave() const;
+
+//    void Print(Option_t *opt = "") const;
+
+    TString GetRule() const;
+    TString GetDataMember() const;
+
+    void SetVariables(const TArrayD &arr);
+
+    ClassDef(MDataChain, 1) // A chain/concatenation of MData objects
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataElement.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataElement.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataElement.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataElement.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataElement.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataElement.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataFormula.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataFormula.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataFormula.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataFormula.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataFormula.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataFormula.h	(revision 3781)
@@ -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;	// Container for the filters
+
+    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-8-4/MagicSoft/Mars/mdata/MDataList.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataList.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataList.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataList.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataList.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataList.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataMember.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataMember.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataMember.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataMember.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataMember.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataMember.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataValue.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataValue.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataValue.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/MDataValue.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataValue.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/MDataValue.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mdata/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mdata/Makefile	(revision 3781)
@@ -0,0 +1,57 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+INCLUDES = -I. -I../mbase -I../mhbase
+
+# @code 
+
+CINT     = Data
+LIB      = mdata.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MData.cc \
+	   MDataArray.cc \
+           MDataElement.cc \
+	   MDataMember.cc \
+	   MDataValue.cc \
+	   MDataList.cc \
+	   MDataChain.cc \
+           MDataFormula.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/merpp.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/merpp.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/merpp.cc	(revision 3781)
@@ -0,0 +1,347 @@
+#include <TSystem.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MRawFileRead.h"
+#include "MSqlInsertRun.h"
+#include "MRawFileWrite.h"
+
+#include "MReportFileRead.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()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   merpp [-h] [-?] [-a] [-vn] [-cn] [-u, -f]" << endl;
+    gLog << "         inputfile[.rep,[.raw],[.txt]] [outputfile[.root]]" << endl << 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;
+    gLog << "     -c#                              Compression level #=1..9 [default=2]" << endl;
+    gLog << "     -v#                              Verbosity level # [default=2]" << endl;
+    gLog << "     -u, --update                     Update file" << endl;
+    gLog << "     -a, --no-colors                  Do not use Ansii color codes" << endl;
+    gLog << "     -f                               Force overwrite of an existing file" << endl;
+    gLog << "     --sql=mysql://user:password@url  Insert run into database <raw data only>" << endl;
+    gLog << "     --start=yyyy-mm-dd/hh:mm:ss.mmm  Start event time for merpping report files" << endl;
+    gLog << "     --stop=yyyy-mm-dd/hh:mm:ss.mmm   Stop  event time for merpping report files" << endl;
+    gLog << "     --run=#                          Only data corresponding to this run number" << endl;
+    gLog << "     --debug[=n]                      Enable root debugging (Default: gDebug=1)" << endl;
+    gLog << "     -?, -h, --help                   This help" << endl << endl;
+    gLog << "   REMARK: At the moment you can process a .raw _or_ a .rep file, only!" << 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;
+}
+
+int main(const int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    if (arg.HasOnly("-?") || arg.HasOnly("-h") || arg.HasOnly("--help"))
+    {
+        Usage();
+        return -1;
+    }
+
+    if (arg.HasOnlyAndRemove("--no-colors") || arg.HasOnlyAndRemove("-a"))
+        gLog.SetNoColors();
+
+    const Int_t kComprlvl = arg.HasOption("-c") ? arg.GetIntAndRemove("-c") : 1;
+    Bool_t kUpdate = arg.HasOnlyAndRemove("--update") || arg.HasOnlyAndRemove("-u");
+    const Bool_t kForce = arg.HasOnlyAndRemove("-f");
+
+    gLog.SetDebugLevel(arg.HasOption("-v") ? arg.GetIntAndRemove("-v") : 2);
+
+    gDebug = arg.HasOption("--debug=") ? arg.GetIntAndRemove("--debug=") : 0;
+    if (gDebug==0 && arg.HasOnlyAndRemove("--debug"))
+        gDebug=1;
+
+    MTime kTimeStart;
+    MTime kTimeStop;
+    if (arg.HasOption("--star="))
+        kTimeStart = AnalyseTime(arg.GetStringAndRemove("--start="));
+    if (arg.HasOption("--stop="))
+        kTimeStop = AnalyseTime(arg.GetStringAndRemove("--stop="));
+
+    const Int_t   kRunNumber   = arg.HasOption("--run=") ? arg.GetIntAndRemove("--run=") : -1;
+    const TString kSqlDataBase(arg.GetStringAndRemove("--sql="));
+
+    if (kTimeStart)
+        gLog << inf << "Start Time: " << kTimeStart << endl;
+    if (kTimeStop)
+        gLog << inf << "Stop  Time: " << kTimeStop << 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;
+    }
+
+    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("MReportDrive",       "Drive");
+            w->AddContainer("MTimeDrive",         "Drive");
+            w->AddContainer("MReportCC",          "CC");
+            w->AddContainer("MTimeCC",            "CC");
+            // w->AddContainer("MReportDAQ",         "DAQ");
+            // w->AddContainer("MTimeDAQ",           "DAQ");
+        }
+        write = w;
+
+        MReportFileRead *r = new MReportFileRead(kNamein);
+        r->SetTimeStart(kTimeStart);
+        r->SetTimeStop(kTimeStop);
+        if (isdc)
+        {
+            r->SetHasNoHeader();
+            r->AddToList("MReportCurrents");
+        }
+        else
+        {
+            r->AddToList("MReportCC");
+            //r->AddToList("MReportDAQ");
+            r->AddToList("MReportDrive");
+            r->AddToList("MReportCamera");
+            r->AddToList("MReportTrigger");
+            if (kRunNumber>0)
+            {
+                r->AddToList("MReportRun");
+                filter = new MFDataMember("MReportRun.fRunNumber", '=', kRunNumber);
+                w->SetFilter(filter);
+            }
+        }
+        read = r;
+    }
+    else
+    {
+        read  = new MRawFileRead(kNamein);
+        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-8-4/MagicSoft/Mars/mfbase/FBaseIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/FBaseIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/FBaseIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/FBaseLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/FBaseLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/FBaseLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfbase/MF.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MF.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MF.cc	(revision 3781)
@@ -0,0 +1,417 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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"
+//
+// 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 << "Trying to resolve 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)
+    {
+        *fLog << err << dbginf << "Syntax Error: No coditional sign found in " << txt << endl;
+        return NULL;
+    }
+    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)
+    {
+        *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->CallProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Postprocess all filters.
+//
+Int_t MF::PostProcess()
+{
+    return fF->CallPostProcess();
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the result of the filter rule.
+//
+Bool_t MF::IsExpressionTrue() const
+{
+    return fF->IsConditionTrue();
+}
+
+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;
+
+}
+
+void MF::Print(Option_t *opt) const
+{
+    *fLog << all << underline << GetDescriptor() << endl;
+    fF->Print();
+    *fLog << endl << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MF.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MF.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MF.h	(revision 3781)
@@ -0,0 +1,52 @@
+#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;
+
+public:
+    MF();
+    MF(const char *text, const char *name=NULL, const char *title=NULL);
+    ~MF();
+
+    Bool_t IsExpressionTrue() const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    void Print(Option_t *opt="") const;
+
+    void SetVariables(const TArrayD &arr) { if (fF) fF->SetVariables(arr); }
+
+    ClassDef(MF, 0) // A Filter for cuts in any data member
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.cc	(revision 3781)
@@ -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  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;
+}
+
+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;
+}
+
+TString MFDataChain::GetRule() const
+{
+    TString ret;// = "{";
+    ret += fData.GetRule();
+    //ret += "}";
+    ret += fFilterType==kELowerThan?"<":">";
+
+    TString str;
+    str += fCond->GetRule();
+    ret += str.Strip(TString::kBoth);
+    return ret;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataChain.h	(revision 3781)
@@ -0,0 +1,58 @@
+#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;
+
+    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-8-4/MagicSoft/Mars/mfbase/MFDataMember.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataMember.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataMember.cc	(revision 3781)
@@ -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  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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataMember.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataMember.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFDataMember.h	(revision 3781)
@@ -0,0 +1,46 @@
+#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;
+
+    void SetVariables(const TArrayD &arr) { fData.SetVariables(arr); }
+
+    ClassDef(MFDataMember, 1) // A Filter for cuts in any data member
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfbase/MFEventSelector.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.cc	(revision 3781)
@@ -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): 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-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MFEventSelector2
+//
+// This is a filter to make a selection of events from a file.
+//
+// see Construtor for more instructions and 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 "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 doesn't matter. To crop the distribution
+//     to a nominal value of total events use SetNumMax
+//  2) The dimension of the MH3 determins the dimension in which the
+//     event selector will work, eg
+//       MH3 hist("MMcEvt.fTelescopeTheta", "MMcEvt.fEnergy");
+//     Would result in a redistribution of Theta and Energy.
+//  3) The given rules are the variables which are used for the
+//     redistribution, eg:
+//       MH3 hist("MMcEvt.fTelescopeTheta");
+//     would result in redistributing Theta.
+//       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 and the binnings)
+//
+
+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)
+{
+    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)
+{
+    if (read.GetEntries() > kMaxUInt) // FIXME: LONG_MAX ???
+    {
+        *fLog << err << "kIntMax exceeded." << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf << underline << endl;
+    *fLog << "MFEventSelector2::ReadDistribution:" << endl;
+    *fLog << " - Start of eventloop to generate the original distribution..." << endl;
+
+    MEvtLoop run(GetName());
+    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.SetBit(MFillH::kDoNotDisplay);
+    tlist.AddToList(&read);
+    tlist.AddToList(&fill);
+    run.SetDisplay(fDisplay);
+    if (!run.Eventloop())
+    {
+        *fLog << err << dbginf << "Evtloop in MFEventSelector2::ReadDistribution failed." << 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;
+
+    return read.Rewind();
+}
+
+// --------------------------------------------------------------------------
+//
+// After reading the histograms the arrays used for the random event
+// selction 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 useorigdist = fHistNom->GetHist().GetEntries()==0;
+    TH1 *hnp =  useorigdist ? (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 (useorigdist)
+      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 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;
+    }
+
+    MRead *read = (MRead*)tasklist->FindObject("MRead");
+    if (!read)
+    {
+        *fLog << err << "MRead not found... abort." << endl;
+        return kFALSE;
+    }
+
+    if (!PreProcessData(parlist))
+        return kFALSE;
+
+    InitHistogram(fHistOrig);
+    InitHistogram(fHistRes);
+
+    fHistNom->SetTitle("Users Nominal Distribution");
+    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
+    if (!ReadDistribution(*read))
+        return kFALSE;
+
+    // Prepare histograms and arrays for selection
+    PrepareHistograms();
+
+    return read->CallPreProcess(parlist);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 counted
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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();
+
+    // Get corresponding bin number and check
+    // whether a selection should be made
+    fResult = Select(fHistNom->FindFixBin(valx, valy, valz)-1);
+
+    fCounter[fResult ? 1 : 0]++;
+
+    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)(fCounter[0]*100/GetNumExecutions())
+            << "%) Events not selected" << endl;
+
+      *fLog << " " << fCounter[0] << " ("
+            << (int)(fCounter[1]*100/GetNumExecutions())
+            << "%) 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-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFEventSelector2.h	(revision 3781)
@@ -0,0 +1,68 @@
+#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
+
+    Bool_t fResult;
+    Int_t  fCounter[2];
+
+    TH1   &InitHistogram(MH3* &hist);
+    Bool_t ReadDistribution(MRead &read);
+    void   PrepareHistograms();
+    Bool_t PreProcessData(MParList *parlist);
+    Bool_t Select(Int_t bin);
+
+    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; }
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+    ClassDef(MFEventSelector2, 0) // FIMXE!
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFRealTimePeriod.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfbase/MFilterList.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFilterList.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFilterList.cc	(revision 3781)
@@ -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, 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();
+//
+// 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.";
+
+// --------------------------------------------------------------------------
+//
+//   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)
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    gROOT->GetListOfCleanups()->Add(&fFilters);
+    fFilters.SetBit(kMustCleanup);
+
+    fFilterType = kEAnd;
+
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+//   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;
+
+    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+")";
+}
+
+void MFilterList::SetVariables(const TArrayD &arr)
+{
+    fFilters.ForEach(MFilter, SetVariables)(arr);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFilterList.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFilterList.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/MFilterList.h	(revision 3781)
@@ -0,0 +1,60 @@
+#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;
+
+public:
+    MFilterList(const char *type="&&", const char *name=NULL, const char *title=NULL);
+    MFilterList(MFilterList &ts);
+    ~MFilterList()
+    {
+        if (TestBit(kIsOwner))
+            fFilters.SetOwner();
+    }
+
+    Bool_t AddToList(MFilter *filter);
+    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;
+
+    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-8-4/MagicSoft/Mars/mfbase/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfbase/Makefile	(revision 3781)
@@ -0,0 +1,56 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+INCLUDES = -I. -I../mbase -I../mdata -I../mfileio -I../mhbase
+
+# @code 
+
+CINT     = FBase
+LIB      = mfbase.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MF.cc \
+           MFilterList.cc \
+           MFEventSelector.cc \
+           MFEventSelector2.cc \
+	   MFDataChain.cc \
+	   MFDataMember.cc \
+           MFRealTimePeriod.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/FileIOLinkDef.h	(revision 3781)
@@ -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 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+;
+
+#pragma link C++ class MCT1ReadAscii+;
+#pragma link C++ class MCT1ReadPreProc+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.cc	(revision 3781)
@@ -0,0 +1,297 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// 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;
+
+    fPedest->InitSize(127);
+
+    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-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadAscii.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.cc	(revision 3781)
@@ -0,0 +1,1172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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
+//    MBlindPixels    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 "MBlindPixels.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->SetPixelBlind(i);
+        }
+    *fLog << endl;
+
+    *fLog << "Exclude pixels: ";
+    // Boolean bexcludepix[iMAXNUMPIX];
+    for (int i=0; i<iMAXNUMPIX; i++)
+        if (outpars.bexcludepix[i])
+        {
+            *fLog << i << " ";
+            fBlinds->SetPixelBlind(i);
+        }
+    *fLog << endl;
+
+    // save blind pixels for all events of this run
+    fBlnd.Set(iMAXNUMPIX);
+    for (int i=0; i<iMAXNUMPIX; i++)
+        fBlnd[i] = fBlinds->IsBlind(i) ? 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->InitSize(iMAXNUMPIX);
+
+    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 = (MBlindPixels*)pList->FindCreateObj("MBlindPixels");
+    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->InitSize(iMAXNUMPIX);
+
+    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->SetPixelBlind(i);
+        }
+
+    // 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-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MCT1ReadPreProc.h	(revision 3781)
@@ -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 MBlindPixels;
+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
+    MBlindPixels  *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-8-4/MagicSoft/Mars/mfileio/MChain.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MChain.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MChain.cc	(revision 3781)
@@ -0,0 +1,60 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MChain                                                                  //
+//                                                                         //
+// Helper class for MReadTree                                              //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MChain.h"
+
+ClassImp(MChain);
+
+Int_t MChain::LoadTree(Int_t entry)
+{
+    //
+    // 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()
+    //
+    TObject *notify = GetNotify();
+
+    SetNotify(this);
+
+    Int_t rc = TChain::LoadTree(entry);
+
+    if (rc >= 0 && fNotified && notify)
+        if (!notify->Notify())
+            rc = -15;
+
+    SetNotify(notify);
+
+    return rc;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MChain.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MChain.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MChain.h	(revision 3781)
@@ -0,0 +1,27 @@
+#ifndef MARS_MChain
+#define MARS_MChain
+
+#ifndef ROOT_TChain
+#include <TChain.h>
+#endif
+
+class MChain : public TChain
+{
+private:
+    Bool_t fNotified;
+
+public:
+    MChain() : TChain(), fNotified(kFALSE) {}
+    MChain(const char *name, const char *title="") : TChain(name, title), fNotified(kFALSE) {}
+
+    void ResetTree() { fTree = 0; fTreeNumber = -1; }
+
+    virtual Bool_t Notify() { fNotified = kTRUE; return kTRUE; }
+    virtual void   SetNotify(TObject *obj) { fNotify = obj; fNotified = kFALSE; }
+
+    Int_t LoadTree(Int_t entry);
+
+    ClassDef(MChain, 1) // Class derived from TChain to give access to Notify-return value
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.cc	(revision 3781)
@@ -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-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 "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;
+}
+
+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
+//
+Bool_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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MRead.h	(revision 3781)
@@ -0,0 +1,33 @@
+#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 Bool_t Rewind();
+
+    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);
+
+    Bool_t ReadEnv(const TEnv &env, TString prefix, Bool_t print);
+
+    ClassDef(MRead, 0)	// Base class for a reading task
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.cc	(revision 3781)
@@ -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@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// 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 "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MTaskList.h"
+
+#include "MRawRunHeader.h"
+#include "MStatusDisplay.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, "ReadRunHeaders");
+
+    //
+    // 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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+    }
+
+    if (fDisplay)
+    {
+        TString txt = GetFileName();
+        txt += " @ ";
+        txt += GetNumEntry()-1;
+        fDisplay->SetStatusLine2(txt);
+    }
+
+    const MMcRunHeader *mcheader = (MMcRunHeader*)fParList->FindObject("MMcRunHeader");
+    if (mcheader)
+    {
+        if (mcheader->GetReflVersion()<=40 && mcheader->GetTelesTheta()>15)
+        {
+            *fLog << warn << "Warning - You may use Monte Carlo data produced with a version" << endl;
+            *fLog << "of the reflector program < 0.4 and a zenith angle > 15," << endl;
+            *fLog << "in this case you may get less photons than you would expect." << endl;
+        }
+        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 - Task List 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-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadMarsFile.h	(revision 3781)
@@ -0,0 +1,35 @@
+#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();
+
+    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-8-4/MagicSoft/Mars/mfileio/MReadReports.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadReports.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadReports.cc	(revision 3781)
@@ -0,0 +1,381 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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;
+}
+
+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!
+//
+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)
+        t->SetBit(kHasMaster);
+
+    if (!fEnableAutoScheme)
+        t->DisableAutoScheme();
+
+    //FIXME!
+    //t->DisableAutoScheme();
+
+    fTrees->AddToList(t);
+    //    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    fList = (MTask*)plist->FindObject("MTaskList");
+
+    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);
+
+        //Int_t before = chain->GetTreeNumber();
+        if (chain->GetEntry(++fPosEntry[nmin])>0)
+        {
+            MTask *task = (MTask*)fTrees->GetList()->At(nmin);
+
+            if (task->CallProcess())
+            {
+                fList->SetStreamId(task->GetName());
+                return kTRUE;
+            }
+        }
+
+        *fLog << dbg << "Removing chain " << chain->GetName() << " from list." << endl;
+
+        delete *GetTime(chain);
+        delete  GetTime(chain);
+        delete fChains->Remove(chain);
+    }
+
+    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, title, GetCpuTime());
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadReports.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadReports.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadReports.h	(revision 3781)
@@ -0,0 +1,64 @@
+#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 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.
+
+    MTask     *fList;     // pointer to the task list to set the stream id
+
+    Bool_t     fEnableAutoScheme;
+
+    MTime** GetTime(TChain *c) const;
+    Int_t   FindNextTime();
+
+    UInt_t  GetEntries() { return 0; }
+
+    Int_t   PreProcess(MParList *plist);
+    Int_t   Process();
+    Int_t   PostProcess();
+
+    //Bool_t  Notify();
+
+    enum {
+        //MReadTree::kChainWasChanged = BIT(14)
+        kHasMaster = BIT(15)
+    };
+
+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!
+
+    ClassDef(MReadReports, 0) // Reads events and reports from a root file ordered in time
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadRflFile.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadRflFile.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadRflFile.cc	(revision 3781)
@@ -0,0 +1,451 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+    //
+    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;
+
+    fIn = new ifstream(name);
+    if (!*fIn)
+    {
+        *fLog << err << "Cannot open file " << name << ": ";
+        *fLog << strerror(errno) << endl;
+        return kFALSE;
+    }
+
+    *fLog << inf;
+    fLog->Separator(name);
+
+    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-8-4/MagicSoft/Mars/mfileio/MReadRflFile.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadRflFile.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadRflFile.h	(revision 3781)
@@ -0,0 +1,60 @@
+#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
+
+    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; }
+
+    Bool_t SearchFor(Int_t runno, Int_t eventno);
+
+    ClassDef(MReadRflFile, 0) // Reads reflector files
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadTree.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadTree.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadTree.cc	(revision 3781)
@@ -0,0 +1,1033 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// 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                                          //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#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 "MLog.h"
+#include "MLogManip.h"
+
+
+ClassImp(MReadTree);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Default constructor. Don't use it.
+//
+MReadTree::MReadTree()
+    : fNumEntry(0), fNumEntries(0), fBranchChoosing(kFALSE), fAutoEnable(kTRUE)
+{
+    fName  = "MRead";
+    fTitle = "Task to loop over all events in one single tree";
+
+    fVetoList = NULL;
+    fNotify = NULL;
+
+    fChain = NULL;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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);
+
+    // 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);
+//        if (fChain->Add(fname)>0)
+//            SetBit(kChainWasChanged);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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!
+    //
+    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;
+
+    delete fNotify;
+    delete fVetoList;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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(fChain->GetStatus()->GetSize());
+    Int_t num=0;
+
+    // Loop over all branches which have a corresponding container
+    TIter Next(fChain->GetStatus());
+
+    TChainElement *element = NULL;
+    while ((element=(TChainElement*)Next()))
+    {
+        // Get branch name and find pointer to corresponding branch
+        const TString name = element->GetName();
+        const TBranch *b = fChain->FindBranch(name);
+
+        // Skip element without corresponding branches (like "*")
+        if (!b)
+            continue;
+
+        entries[num++] = (Int_t)b->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 (" << fChain->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.
+//
+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 (!fNotify)
+        return kTRUE;
+
+    TIter Next(fNotify);
+    TObject *o=NULL;
+    while ((o=Next()))
+        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 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() << " - AddFile: " << numfiles << " files added from " << fname << "." << 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)
+{
+    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()
+{
+    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;
+    fChain->SetBranchStatus("*", kFALSE);
+    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->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)
+{
+    fChain->SetBranchStatus(name, status);
+
+    *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 (fChain->GetBranch(bn))
+        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 (fChain->GetBranch(dot+1))
+        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))
+    {
+        *fLog << inf << "Scanning chain " << fChain->GetName() << "... " << flush;
+        fNumEntries = (UInt_t)fChain->GetEntries();
+        *fLog << fNumEntries << " events found." << endl;
+        ResetBit(kChainWasChanged);
+    }
+    return 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)
+{
+    //
+    // Make sure, that all the following calls doesn't result in
+    // Notifications. This may be dangerous, because the notified
+    // tasks are not preprocessed.
+    //
+    fChain->SetNotify(NULL);
+
+    //
+    // check for files and for the tree!
+    //
+    if (!fChain->GetFile())
+    {
+        *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(fChain->GetListOfBranches());
+    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.
+        //
+        TChainElement *element = (TChainElement*)fChain->GetStatus()->FindObject(bname);
+        if (element)
+            delete (MParContainer**)element->GetBaddress();
+
+        //
+        // here pcont is a pointer the to container in which the data from
+        // the actual branch should be stored - enable branch.
+        //
+        fChain->SetBranchAddress(bname, pcont);
+
+        *fLog << inf << "Master branch address " << bname << " [";
+        *fLog << classname << "] 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.
+    //
+    fChain->ResetTree();
+    fChain->SetNotify(this);
+
+    return GetSelector() ? GetSelector()->CallPreProcess(pList) : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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)
+{
+    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 = fChain->GetEntry(fNumEntry++) != 0;
+
+    if (rc)
+        SetReadyToSave();
+
+    return rc;
+}
+
+// --------------------------------------------------------------------------
+//
+//  If a selector is given the selector is post processed
+//
+Int_t MReadTree::PostProcess()
+{
+    return GetSelector() ? GetSelector()->CallPostProcess() : kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Get the Event with the current EventNumber fNumEntry
+//
+Bool_t MReadTree::GetEvent()
+{
+    Bool_t rc = fChain->GetEntry(fNumEntry) != 0;
+
+    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::GetFileName() const
+{
+    const TFile *file = fChain->GetFile();
+
+    if (!file)
+        return TString("<unknown>");
+
+    TString name(file->GetName());
+    name.Remove(0, name.Last('/')+1);
+    return name;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Return the number of the file in the chain, -1 in case of an error
+//
+Int_t MReadTree::GetFileIndex() const
+{
+    return fChain->GetTreeNumber();
+    /*
+    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-8-4/MagicSoft/Mars/mfileio/MReadTree.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadTree.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MReadTree.h	(revision 3781)
@@ -0,0 +1,85 @@
+#ifndef MARS_MReadTree
+#define MARS_MReadTree
+
+#ifndef MARS_MRead
+#include "MRead.h"
+#endif
+
+class MChain;
+class TBranch;
+
+class MReadTree : public MRead
+{
+    friend class MReadReports;
+
+private:
+    MChain *fChain;            // 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
+
+    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();
+    MReadTree(const char *treename, const char *filename=NULL, const char *name=NULL, const char *title=NULL);
+    ~MReadTree();
+
+    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;
+    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 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-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.cc	(revision 3781)
@@ -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, 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 "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() const
+{
+    Bool_t written = kFALSE;
+
+    MParContainer *obj = NULL;
+
+    Int_t num = fList.GetEntries();
+
+    TIter Next(&fList);
+    while ((obj=(MParContainer*)Next()))
+    {
+        //
+        // Check for the Write flag
+        //
+        if (!obj->IsReadyToSave())
+            continue;
+
+        //
+        // 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 - given number of objects doesn't fit number of written objects." << 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-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteAsciiFile.h	(revision 3781)
@@ -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() const;
+    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-8-4/MagicSoft/Mars/mfileio/MWriteFile.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteFile.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteFile.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfileio/MWriteFile.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteFile.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteFile.h	(revision 3781)
@@ -0,0 +1,25 @@
+#ifndef MARS_MWriteFile
+#define MARS_MWriteFile
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MWriteFile : public MTask
+{
+private:
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+    Bool_t ReInit(MParList *pList);
+
+    virtual Bool_t      IsFileOpen() const = 0;
+    virtual Bool_t      CheckAndWrite() const = 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-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.cc	(revision 3781)
@@ -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): Thomas Bretz, 6/2001 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// 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: Checkout the Warning in MTaskList.                             //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+#include "MWriteRootFile.h"
+
+#include <fstream>
+
+#include <TFile.h>
+#include <TTree.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+ClassImp(MRootFileBranch);
+ClassImp(MWriteRootFile);
+
+using namespace std;
+
+static const TString gsDefName  = "MWriteRootFile";
+static const TString gsDefTitle = "Task which writes a root-output file";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. It is there to support some root stuff.
+// Don't use it.
+//
+MWriteRootFile::MWriteRootFile() : fOut(NULL)
+{
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    fBranches.SetOwner();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+MWriteRootFile::MWriteRootFile(const char *fname,
+                               const Option_t *opt,
+                               const char *ftitle,
+                               const Int_t comp,
+                               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();
+
+    //
+    // Believing the root user guide, TTree instanced are owned by the
+    // directory (file) in which they are. This means we don't have to
+    // care about their destruction.
+    //
+    //fTrees.SetOwner();
+
+    TString str(fname);
+    if (!str.EndsWith(".root", TString::kIgnoreCase))
+        str += ".root";
+
+    //
+    // Open the rootfile
+    //
+    fOut = new TFile(str, opt, ftitle, comp);
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints some statistics about the file to the screen. And closes the file
+// properly.
+//
+MWriteRootFile::~MWriteRootFile()
+{
+    //
+    // Print some statistics to the looging out.
+    //
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Prints all trees with the actually number of written entries to log-out.
+//
+void MWriteRootFile::Print(Option_t *) const
+{
+    *fLog << all << underline << "File: " << GetFileName() << 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" << branch->GetEntries() << " entries." << endl;
+    }
+
+    TTree *t = NULL;
+    TIter NextTree(&fTrees);
+    while ((t=(TTree*)NextTree()))
+        if (t->TestBit(kIsNewTree))
+            *fLog << " " << t->GetName() << ": \t" << t->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)
+{
+    //
+    // 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)
+{
+    //
+    // 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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()));
+
+        //
+        // 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)
+        //
+        TTree *tree = (TTree*)fOut->Get(tname);
+        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;
+            fOut->cd();
+
+            tree = new TTree(tname, ttitle);
+            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);
+
+            gDirectory = save;
+
+            *fLog << inf << "Tree " << tname << " created." << endl;
+        }
+
+        //
+        // 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());
+        }
+        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 << " of " << 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;
+        }
+
+        //
+        // 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() const
+{
+    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
+    //
+    TIter NextTree(&fTrees);
+    while ((obj=NextTree()))
+    {
+        TTree *t = (TTree*)obj;
+
+        //
+        // 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;
+        }
+    }
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// return open state of the root file.
+//
+Bool_t MWriteRootFile::IsFileOpen() const
+{
+    return fOut->IsOpen();
+}
+
+// --------------------------------------------------------------------------
+//
+// return name of the root-file
+//
+const char *MWriteRootFile::GetFileName() const
+{
+    return fOut->GetName();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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() << "(\"";
+    out << fOut->GetName() << "\", \"";
+    out << fOut->GetOption() << "\", \"";
+    out << fOut->GetTitle() << "\", ";
+    out << fOut->GetCompressionLevel();
+
+    if (fName!=gsDefName || fTitle!=gsDefTitle)
+    {
+        out << ", \"" << fName << "\"";
+        if (fTitle!=gsDefTitle)
+            out << ", \"" << fTitle << "\"";
+    }
+    out << ");" << 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-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/MWriteRootFile.h	(revision 3781)
@@ -0,0 +1,112 @@
+#ifndef MARS_MWriteRootFile
+#define MARS_MWriteRootFile
+
+#ifndef MARS_MWriteFile
+#include "MWriteFile.h"
+#endif
+#ifndef ROOT_TObjArray
+#include <TObjArray.h>
+#endif
+
+class TFile;
+class TTree;
+class TBranch;
+
+class MRootFileBranch : public TNamed
+{
+private:
+    TTree         *fTree;       //!
+    TBranch       *fBranch;     //!
+
+    MParContainer *fContainer;
+    TString        fContName;
+
+    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);
+        fContName = "";
+    }
+
+    MRootFileBranch(const char *cname, const char *tname=NULL, Bool_t must=kFALSE)
+        : fTree(NULL), fBranch(NULL), fContainer(NULL), fMust(0)
+    {
+        Init(tname, must);
+        fContName = cname;
+    }
+
+    MRootFileBranch(MParContainer *cont, const char *tname=NULL, Bool_t must=kFALSE)
+        : fTree(NULL), fBranch(NULL), fContName(""), fMust(0)
+    {
+        Init(tname, must);
+        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 fContName; }
+    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:
+    TFile *fOut;
+
+    TObjArray fBranches;
+    TObjArray fTrees;     //!
+
+    //UInt_t fNumEvents; //! Number of events written in a run
+
+    Bool_t      CheckAndWrite() const;
+    Bool_t      IsFileOpen() const;
+    Bool_t      GetContainer(MParList *pList);
+    const char *GetFileName() const;
+
+    void StreamPrimitive(ofstream &out) const;
+    //Bool_t ReInit(MParList *pList);
+
+    enum {
+        kFillTree  = BIT(14),
+        // TBranch::kAutoDelete = BIT(15)
+        // TBranchElement::kDeleteObject = BIT(16)
+        kIsNewTree = BIT(17)
+    };
+
+public:
+    MWriteRootFile();
+    MWriteRootFile(const char *fname,
+                   const Option_t *opt="RECREATE",
+                   const char *ftitle="Untitled",
+                   const Int_t comp=9,
+                   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 Print(Option_t *t=NULL) const;
+
+    ClassDef(MWriteRootFile, 1)	// Task to write data into a root file
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/Makefile	(revision 3781)
@@ -0,0 +1,70 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+INCLUDES = -I. -I../mbase -I../mraw -I../mmc -I../mreflector -I../mgui \
+	   -I../mdata -I../manalysis -I../mgeom -I../mhbase -I../mpointing
+#mraw:       MRawRunHeader (MReadMaraFile)
+#mmc:        MMcRunHeader  (MReadMarsFile)
+#mreflector: MRfl*         (MReadRflFile)
+#mgui:       MCamEvent     (MReadRflFile)
+#mdata:      MData*        (MWriteAsciiFile)
+#manalysis:  MCerPhotEvt   (MCT1ReadAscii)
+#mgeom:      MGeomCam      (MCT1ReadPreProc)
+#mhbase:     MBinning      (MCT1ReadPreProc)
+#mpointing:  MPointingPos  (MCT1ReadPreProc)
+
+# @code 
+
+CINT     = FileIO
+LIB      = mfileio.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MRead.cc \
+           MChain.cc \
+	   MReadTree.cc \
+           MReadReports.cc \
+           MReadMarsFile.cc \
+           MReadRflFile.cc \
+           MWriteFile.cc \
+           MWriteAsciiFile.cc \
+           MWriteRootFile.cc \
+           MCT1ReadAscii.cc \
+           MCT1ReadPreProc.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/defines.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/defines.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/defines.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfileio/structures.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/structures.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/structures.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfileio/structures_rfl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/structures_rfl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfileio/structures_rfl.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/FilterIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/FilterIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/FilterIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/FilterLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/FilterLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/FilterLinkDef.h	(revision 3781)
@@ -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 MFAlpha+;
+#pragma link C++ class MFTriggerLvl1+;
+#pragma link C++ class MFTriggerLvl2+;
+#pragma link C++ class MFGeomag+;
+#pragma link C++ class MFParticleId+;
+
+#pragma link C++ class MFCT1SelBasic+;
+#pragma link C++ class MFCT1SelStandard+;
+#pragma link C++ class MFCT1SelFinal+;
+#pragma link C++ class MFSelBasic+;
+#pragma link C++ class MFSelStandard+;
+#pragma link C++ class MFSelFinal+;
+#pragma link C++ class MFSoftwareTrigger+;
+#pragma link C++ class MFCosmics+;
+
+#pragma link C++ class MFEnergySlope+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFAlpha.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFAlpha.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFAlpha.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFAlpha.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFAlpha.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFAlpha.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelBasic.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelFinal.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCT1SelStandard.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFCosmics.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCosmics.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCosmics.cc	(revision 3781)
@@ -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): 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;
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MFCosmics::MFCosmics(const char *name, const char *title)
+    : fPedestals(NULL), fSignals(NULL),
+      fRawEvt(NULL), fMaxEmptyPixels(0.4)
+{
+    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("MPedestalCam");
+    if (!fPedestals)
+    {
+        *fLog << err << "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-8-4/MagicSoft/Mars/mfilter/MFCosmics.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCosmics.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFCosmics.h	(revision 3781)
@@ -0,0 +1,48 @@
+#ifndef MARS_MFCosmics
+#define MARS_MFCosmics
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MRawEvtData;
+
+class MPedestalCam;
+class MExtractedSignalCam;
+
+class MFCosmics : public MFilter
+{
+private:
+    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)
+
+    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; }
+
+    ClassDef(MFCosmics, 0)   // Filter to perform a cosmics rejection
+};
+
+#endif
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFEnergySlope.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFGeomag.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFGeomag.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFGeomag.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFGeomag.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFGeomag.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFGeomag.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFParticleId.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFParticleId.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFParticleId.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFParticleId.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFParticleId.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFParticleId.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFSelBasic.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelBasic.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelBasic.cc	(revision 3781)
@@ -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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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
+//      software trigger fullfilled (with minimum no.of photons = minphotons)
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+
+#include "MFSelBasic.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(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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the cut values
+// 
+//
+void MFSelBasic::SetCuts(Float_t minphotons, 
+                            Float_t thetamin, Float_t thetamax)
+{
+    fMinPhotons = minphotons;
+    fThetaMin   = thetamin;
+    fThetaMax   = thetamax;
+
+    *fLog << inf << "MFSelBasic cut values : fMinPhotons, fThetaMin, fThetaMax = ";
+    *fLog << fMinPhotons <<",  " << fThetaMin << ",  " << fThetaMax << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+    }
+
+    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 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 = 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 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[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-8-4/MagicSoft/Mars/mfilter/MFSelBasic.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelBasic.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelBasic.h	(revision 3781)
@@ -0,0 +1,68 @@
+#ifndef MARS_MFSelBasic
+#define MARS_MFSelBasic
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MFSelBasic                                                           //
+//                                                                         //
+// Class to evaluate basic cuts                                            //
+//                                                                         //
+/////////////////////////////////////////////////////////////////////////////
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MGeomCam;
+class MCerPhotEvt;
+class MPedestalCam;
+class MRawRunHeader;
+
+class MFSelBasic : 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:
+    MFSelBasic(const char *name=NULL, const char *title=NULL);
+
+    void SetCuts(Float_t minphotons, Float_t thetamin, Float_t thetamax);
+
+    ClassDef(MFSelBasic, 0)   // Class to evaluate basic cuts
+};
+
+#endif
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelFinal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelFinal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelFinal.cc	(revision 3781)
@@ -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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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;
+
+    *fLog << inf << "MFSelFinal cut values : fHadronnessMax, fAlphaMax, fDistMax = ";
+    *fLog << fHadronnessMax << ",  " << fAlphaMax << ",  " << fDistMax <<  endl;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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));
+
+    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-8-4/MagicSoft/Mars/mfilter/MFSelFinal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelFinal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelFinal.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFSelStandard.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelStandard.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelStandard.cc	(revision 3781)
@@ -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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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;
+
+    *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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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));
+
+    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-8-4/MagicSoft/Mars/mfilter/MFSelStandard.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelStandard.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSelStandard.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.cc	(revision 3781)
@@ -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): 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MFSoftwareTrigger
+//
+//  This is a class to evaluate a software trigger
+//
+//  to be called after the calibration (when the number of photons is
+//               available for all pixels)
+//
+// require 2 neighboring pixels (which are not in the outermost ring),
+//                       each having at least 'fNumMinPhotons' photons
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MFSoftwareTrigger.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotEvt.h"
+
+ClassImp(MFSoftwareTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MFSoftwareTrigger::MFSoftwareTrigger(const char *name, const char *title)
+    : fNumMinPhotons(0), fNumNeighbors(2)
+{
+    fName  = name  ? name  : "MFSoftwareTrigger";
+    fTitle = title ? title : "Filter for software trigger";
+}
+
+// --------------------------------------------------------------------------
+//
+// Software trigger
+// 
+// require 2 neighboring pixels (which are not in the outermost ring), 
+//                       each having at least 'fNumMinPhotons' photons
+// 
+Bool_t MFSoftwareTrigger::SwTrigger() const
+{
+    const Int_t entries = fEvt->GetNumPixels();
+ 
+    for (Int_t i=0; i<entries; i++)
+    {
+        const MCerPhotPix &pix = (*fEvt)[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        if (pix.GetNumPhotons()<fNumMinPhotons)
+            continue;
+
+        // this pixel is used and has the required no.of photons
+        // check whether this is also true for a neigboring pixel
+        MGeomPix &gpix = (*fCam)[pix.GetPixId()];
+        if (gpix.IsInOutermostRing())
+            continue;
+
+        Int_t num = 1;
+
+        const Int_t nneighbors = gpix.GetNumNeighbors();
+        for (Int_t n=0; n<nneighbors; n++)
+        {
+            const Int_t id = gpix.GetNeighbor(n);
+            if (!fEvt->IsPixelUsed(id))
+                continue;
+
+            if ((*fCam)[id].IsInOutermostRing())
+                continue;
+
+            const Double_t photons = fEvt->GetPixById(id)->GetNumPhotons();
+            if (photons >= fNumMinPhotons)
+                if (++num==fNumNeighbors)
+                    return kTRUE;
+        }
+    }
+    return kFALSE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Request pointer to MCerPhotEvt and MGeomCam from paremeter list
+//
+Int_t MFSoftwareTrigger::PreProcess(MParList *pList)
+{
+    fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MCerPhotEvt 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()
+{
+    fResult = SwTrigger();
+
+    fCut[fResult ? 0 : 1]++;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Prints some statistics about the Basic selections.
+//
+Int_t MFSoftwareTrigger::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 << "%) Evts fullfilled software trigger";
+    *fLog << " (NumPhotons>=" << fNumMinPhotons << ", NumNeighbors>=";
+    *fLog << (int)fNumNeighbors << ")" << endl;
+    *fLog << " " << setw(7) << fCut[1] << " (" << setw(3) ;
+    *fLog << (int)(fCut[1]*100/GetNumExecutions());
+    *fLog << "%) Evts didn't fullfill software trigger."  << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFSoftwareTrigger.h	(revision 3781)
@@ -0,0 +1,42 @@
+#ifndef MARS_MFSoftwareTrigger
+#define MARS_MFSoftwareTrigger
+
+#ifndef MARS_MFilter
+#include "MFilter.h"
+#endif
+
+class MMcEvt;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MFSoftwareTrigger : public MFilter
+{
+private:
+    const MGeomCam    *fCam; // Camera Geometry
+    const MCerPhotEvt *fEvt; // Cerenkov Photon Event
+
+    Float_t     fNumMinPhotons; // nuber of minimum required photons
+    Byte_t      fNumNeighbors;  // number of required neighbours
+
+    Int_t       fCut[2];
+
+    Bool_t      fResult;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Bool_t SwTrigger() const;
+
+    Bool_t IsExpressionTrue() const { return fResult; }
+
+public:
+    MFSoftwareTrigger(const char *name=NULL, const char *title=NULL);
+
+    void SetNumMinPhotons(Float_t minphotons) { fNumMinPhotons = minphotons; }
+    void SetNumNeighbors(Byte_t num) { fNumNeighbors = num; }
+
+    ClassDef(MFSoftwareTrigger, 0) // Filter for software trigger
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl1.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/MFTriggerLvl2.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/Makefile	(revision 3781)
@@ -0,0 +1,65 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+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
+
+# @code 
+
+CINT     = Filter
+LIB      = mfilter.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MFTriggerLvl1.cc \
+	   MFTriggerLvl2.cc \
+	   MFGeomag.cc \
+	   MFParticleId.cc \
+	   MFAlpha.cc \
+	   MFCT1SelBasic.cc \
+	   MFCT1SelStandard.cc \
+	   MFCT1SelFinal.cc \
+	   MFSelBasic.cc \
+	   MFSelStandard.cc \
+	   MFSelFinal.cc \
+           MFSoftwareTrigger.cc \
+           MFCosmics.cc \
+	   MFEnergySlope.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/gcminus.txt
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/gcminus.txt	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/gcminus.txt	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfilter/gcplus.txt
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/gcplus.txt	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfilter/gcplus.txt	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mfit/MTFitLoop.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfit/MTFitLoop.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfit/MTFitLoop.cc	(revision 3781)
@@ -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): 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 <TMinuit.h>
+#include <TStopwatch.h>
+
+#include "MParList.h"
+#include "MRead.h"
+#include "MEvtLoop.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+//------------------------------------------------------------------------
+//
+// 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 = 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: ";
+        for (Int_t i=0; i<7; 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()
+{
+    fDebug     = -1;
+    fNumEvents = -1;
+}
+
+void MTFitLoop::Optimize(MEvtLoop &loop)
+{
+    *fLog << inf << "Event loop was setup" << endl;
+    MParList *parlist = loop->GetParList();
+    if (!parlist)
+        return;
+
+    MParContainer *pars = plist->FindObject(fParametersName);
+    if (!pars)
+        return;
+
+    fEvtLoop = evtloop;
+
+    MParContainer &parameters = *pars;
+
+    TMinuit *minsave = gMinuit;
+
+    gMinuit = new TMinuit(parameters.GetSize());
+    gMinuit->SetPrintLevel(-1);
+
+    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(1000))
+    {
+        *fLog << err << dbginf << "SetErrorDef failed." << endl;
+        return;
+    }
+
+    //
+    // Set starting values and step sizes for parameters
+    //
+    for (Int_t i=0; i<parameters.GetSize(); i++)
+    {
+        TString name = "par[";
+        name += i;
+        name += "]";
+        Double_t vinit = parameters[i];
+        Double_t step  = fabs(parameters[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<parameters.GetSize(); i++)
+        if (i<fFixParams.GetSize() && fFixParams[i]!=0)
+            gMinuit->FixParameter(i);
+        else
+            gMinuit->Release(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<parameters.GetSize(); i++)
+    {
+        Double_t x1, x2;
+        gMinuit->GetParameter(i,x1,x2);
+        parameters[i] = x1;
+        cout << i << ": " << parameters[i] << endl;
+    }
+
+    list.SetVariables(parameters);
+
+    gMinuit = minsave;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mfit/MTFitLoop.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mfit/MTFitLoop.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mfit/MTFitLoop.h	(revision 3781)
@@ -0,0 +1,46 @@
+#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;
+
+public:
+    MTFitLoop();
+
+    void Optimize(MEvtLoop &loop);
+
+    void SetNameParameters(const char *parm) { fParametersName = parm; }
+    void SetFitParameter(const char *parm)   { fFitParameter   = parm; }
+
+    void SetFixedParameters(const TArrayC &c) { fFixedParams = c; }
+
+    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-8-4/MagicSoft/Mars/mgeom/GeomIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/GeomIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/GeomIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/GeomLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/GeomLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/GeomLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCam.cc	(revision 3781)
@@ -0,0 +1,349 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <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), 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;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    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
+{
+    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());
+}
+
+/*
+void MGeomCam::Streamer(TBuffer &R__b)
+{
+   // Stream an object of class MGeomCam.
+
+    if (R__b.IsReading())
+    {
+        MGeomCam::Class()->ReadBuffer(R__b, this);
+
+        UInt_t R__s, R__c;
+        Version_t R__v = b.ReadVersion(&R__s, &R__c);
+        if (R__v > 2) {
+            MGeomCam::Class()->ReadBuffer(b, this, R__v, R__s, R__c);
+
+        Version_t v = MGeomCam::Class()->GetClassVersion();
+   }
+   else
+   {
+       MGeomCam::Class()->WriteBuffer(R__b, this);
+   }
+}
+*/
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCam.h	(revision 3781)
@@ -0,0 +1,91 @@
+#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 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();
+    void InitGeometry()
+    {
+        CalcNumSectors();
+        CalcNumAreas();
+        CalcMaxRadius();
+        CalcPixRatio();
+        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.
+
+    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);
+    }
+
+    virtual void Print(Option_t *opt=NULL)   const;
+
+    ClassDef(MGeomCam, 4)  // Geometry base class for the camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamCT1Daniel.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamECO1000HG.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagic919.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCamMagicHG.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomCorsikaCT.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomMirror.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomMirror.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomMirror.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomMirror.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomMirror.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomMirror.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomPMT.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPMT.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPMT.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomPMT.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPMT.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPMT.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgeom/MGeomPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPix.cc	(revision 3781)
@@ -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-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::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-8-4/MagicSoft/Mars/mgeom/MGeomPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/MGeomPix.h	(revision 3781)
@@ -0,0 +1,74 @@
+#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);
+
+    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 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; }
+    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-8-4/MagicSoft/Mars/mgeom/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgeom/Makefile	(revision 3781)
@@ -0,0 +1,58 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Geom
+
+#
+# Library name to creatre
+#
+LIB   = mgeom.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../MBase
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+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
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/GuiLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgui/MAitoff.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MAitoff.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MAitoff.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgui/MAitoff.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MAitoff.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MAitoff.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgui/MCamEvent.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MCamEvent.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MCamEvent.cc	(revision 3781)
@@ -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): 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"
+
+ClassImp(MCamEvent);
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MCamEvent.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MCamEvent.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MCamEvent.h	(revision 3781)
@@ -0,0 +1,20 @@
+#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;
+
+    ClassDef(MCamEvent, 0) // A camera event
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MHexagon.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MHexagon.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MHexagon.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgui/MHexagon.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MHexagon.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/MHexagon.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mgui/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mgui/Makefile	(revision 3781)
@@ -0,0 +1,48 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Gui
+
+#
+# Library name to creatre
+#
+LIB   = mgui.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgeom
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MHexagon.cc \
+	   MCamEvent.cc
+           
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseIncl.h	(revision 3781)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/HBaseLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhbase/MBinning.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MBinning.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MBinning.cc	(revision 3781)
@@ -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, 01/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MBinning                                                                //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MBinning.h"
+
+#include <ctype.h>      // tolower
+#include <fstream>
+
+#include <TH1.h>        // InheritsFrom
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+
+ClassImp(MBinning);
+
+using namespace std;
+
+static const TString gsDefName  = "MBinning";
+static const TString 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;
+}
+
+void MBinning::SetEdges(const TAxis &axe)
+{
+    const TArrayD &arr = *((TAxis&)axe).GetXbins();
+    if (arr.GetSize()>0)
+    {
+        SetEdges(arr);
+        return;
+    }
+
+    SetEdges(axe.GetNbins(), axe.GetXmin(), axe.GetXmax());
+}
+
+void MBinning::SetEdges(const TH1 &h, const Char_t axis)
+{
+    TH1 &hist = (TH1&)h; // get rid of const qualifier
+    switch (tolower(axis))
+    {
+    case 'x':
+        SetEdges(*hist.GetXaxis());
+        return;
+    case 'y':
+        SetEdges(*hist.GetYaxis());
+        return;
+    case 'z':
+        SetEdges(*hist.GetZaxis());
+        return;
+    default:
+        *fLog << warn << "MBinning::SetEdges: Axis '" << axis << "' unknown... using x." << endl;
+        SetEdges(*hist.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 = (up-lo)/nbins;
+    fEdges.Set(nbins+1);
+    for (int i=0; i<=nbins; i++)
+            fEdges[i] = binsize*i + lo;
+
+    fType = kIsLinear;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MBinning.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MBinning.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MBinning.h	(revision 3781)
@@ -0,0 +1,86 @@
+#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 MBinning : public MParContainer
+{
+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);
+
+    void SetEdges(const TArrayD &arr)
+    {
+        fEdges = arr;
+        fType = kIsUserArray;
+    }
+
+    void SetEdges(const TAxis &axe);
+    void SetEdges(const TH1 &h, const Char_t axis='x');
+    void SetEdges(const Int_t nbins, const Axis_t lo, Axis_t up);
+    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 (((TArrayD)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;
+    }
+
+    // FIXME: ROOT workaround: "operator[] const" missing
+    Double_t GetEdgeLo() const { return ((TArrayD)fEdges)[0]; }
+    Double_t GetEdgeHi() const { return ((TArrayD)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(); }
+
+    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; }
+
+    void Apply(TH1 &);
+
+    ClassDef(MBinning, 1) //Container to store the binning of a histogram
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MFillH.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MFillH.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MFillH.cc	(revision 3781)
@@ -0,0 +1,607 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  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.                                     //
+//                                                                          //
+//  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 = "Fill " + fHName;
+    if (fParContainerName.IsNull())
+        return;
+
+    fTitle += " from " + fParContainerName;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 = "Fill " + fHName + " from " + par->GetDescriptor();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 = (TString)"Fill " + hist->GetDescriptor();
+    if (!par)
+        return;
+
+    fTitle += " from " + fParContainerName;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 = (TString)"Fill " + hist->GetDescriptor() + " from " + par->GetDescriptor();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+//
+Bool_t MFillH::DrawToDisplay()
+{
+    fCanvas = NULL;
+
+    if (!fDisplay)
+        return kTRUE;
+
+    if (!fH->OverwritesDraw())
+        return kTRUE;
+
+    if (TestBit(kDoNotDisplay))
+        return kTRUE;
+
+    fCanvas = &fDisplay->AddTab(fNameTab.IsNull() ? fH->GetName() : fNameTab.Data());
+    fH->Draw();
+
+    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());
+    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.");
+
+        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();
+
+    Bool_t rc = fH->Fill(fParContainer, fWeight?fWeight->GetWeight():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))
+    {
+        fCanvas->cd();
+        fH->DrawClone("nonew");
+        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-8-4/MagicSoft/Mars/mhbase/MFillH.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MFillH.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MFillH.h	(revision 3781)
@@ -0,0 +1,76 @@
+#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 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; }
+
+    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-8-4/MagicSoft/Mars/mhbase/MH.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH.cc	(revision 3781)
@@ -0,0 +1,1179 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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"
+
+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)
+{
+    //
+    //   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
+
+    //
+    // 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());
+#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
+
+    //
+    // 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());
+#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
+
+    //
+    // 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());
+#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;
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    //
+    // Draw first histogram
+    //
+    hist1.Draw();
+    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(gROOT);
+    }
+
+    // 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();
+    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(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(gROOT);
+    }
+
+    // Second loop to fill the histogram
+    for (Int_t i=0;i<size;i++)
+        h1->Fill(array[i]);
+
+    return h1;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH.h	(revision 3781)
@@ -0,0 +1,108 @@
+#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 TCanvas;
+
+class MBinning;
+class MParList;
+
+class MH : public MParContainer
+{
+private:
+    Byte_t fSerialNumber;
+
+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); }
+
+    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 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);
+
+    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 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, 1) //A base class for Mars histograms
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH3.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH3.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH3.cc	(revision 3781)
@@ -0,0 +1,722 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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.
+//
+// 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;
+
+static const TString gsDefName  = "MH3";
+static const TString gsDefTitle = "Container for a %dD 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 = Form(gsDefTitle.Data(), 1);
+
+    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 = Form(gsDefTitle.Data(), 1);
+
+    fHist->UseCurrentStyle();
+    fHist->SetDirectory(NULL);
+    fHist->SetYTitle("Counts");
+
+    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 = Form(gsDefTitle.Data(), 2);
+
+    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 = Form(gsDefTitle.Data(), 3);
+
+    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 (binsz->IsLogarithmic())
+            fHist->SetBit(kIsLogz);
+        if (fData[2]) fHist->SetZTitle(fData[2]->GetTitle());
+        if (fData[2] && !fData[2]->PreProcess(plist))
+            return kFALSE;
+    case 2:
+        binsy = (MBinning*)plist->FindObject(bname+"Y", "MBinning");
+        if (!binsy)
+        {
+            *fLog << err << dbginf << "MBinning '" << bname << "Y' not found... aborting." << endl;
+            return kFALSE;
+        }
+        if (binsy->IsLogarithmic())
+            fHist->SetBit(kIsLogy);
+        if (fData[1]) fHist->SetYTitle(fData[1]->GetTitle());
+        if (fData[1] && !fData[1]->PreProcess(plist))
+            return kFALSE;
+    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 (binsx->IsLogarithmic())
+            fHist->SetBit(kIsLogx);
+
+      if (fData[0]!=NULL)  fHist->SetXTitle(fData[0]->GetTitle());
+        if (fData[0] && !fData[0]->PreProcess(plist))
+            return kFALSE;
+    }
+
+    fHist->SetName(fName);
+
+    TString title("Histogram for ");
+    title += fName;
+
+    switch (fDimension)
+    {
+    case 1:
+        fHist->SetTitle(title+" (1D)");
+        SetBinning(fHist, binsx);
+        return kTRUE;
+    case 2:
+        fHist->SetTitle(title+" (2D)");
+        SetBinning((TH2*)fHist, binsx, binsy);
+        return kTRUE;
+    case 3:
+        fHist->SetTitle(title+" (3D)");
+        SetBinning((TH3*)fHist, binsx, binsy, binsz);
+        return kTRUE;
+    }
+    cout << "Still alive...?" << endl;
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the histogram ant the MH3 container
+//
+void MH3::SetName(const char *name)
+{
+    fHist->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the histogram ant the MH3 container
+//
+void MH3::SetTitle(const char *title)
+{
+    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);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw clone of histogram. So that the object can be deleted
+//
+// 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)
+//
+// If the kIsLog?-Bit is set the axis is displayed lkogarithmically.
+// eg this is set when applying a logarithmic MBinning
+//
+// 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 *MH3::DrawClone(Option_t *opt) const
+{
+    TString str(opt);
+
+    TVirtualPad *c = gPad;
+    if (!str.Contains("nonew", TString::kIgnoreCase))
+    {
+        c = MH::MakeDefCanvas(fHist);
+
+        //
+        // This is necessary to get the expected bahviour of DrawClone
+        //
+        gROOT->SetSelectedPad(NULL);
+    }
+
+    if (str.Contains("COL", TString::kIgnoreCase))
+        SetColors();
+
+    Bool_t only = str.Contains("ONLY", TString::kIgnoreCase) && fDimension==2;
+    if (!only)
+        fHist->DrawCopy(opt);
+
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX("_pfx", -1, 9999, "s");
+        p->SetLineColor(kBlue);
+        p->Draw(only?"":"same");
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY("_pfy", -1, 9999, "s");
+        p->SetLineColor(kBlue);
+        p->Draw(only?"":"same");
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+    }
+
+    if (fHist->TestBit(kIsLogx)) c->SetLogx();
+    if (fHist->TestBit(kIsLogy)) c->SetLogy();
+    if (fHist->TestBit(kIsLogz)) c->SetLogz();
+
+    c->Modified();
+    c->Update();
+
+    return c;
+}
+*/
+
+// --------------------------------------------------------------------------
+//
+// 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)
+//
+// 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);
+
+    AppendPad("");
+
+    TString str(opt);
+
+    // FIXME: Do it in Paint()
+    if (str.Contains("COL", TString::kIgnoreCase))
+        SetColors();
+
+    fHist->SetFillStyle(4000);
+
+    Bool_t only = str.Contains("ONLY", TString::kIgnoreCase) && fDimension==2;
+    if (!only)
+        fHist->Draw(opt);
+
+    if (str.Contains("PROFX", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileX("_pfx", -1, 9999, "s");
+        p->SetLineColor(kBlue);
+        p->Draw(only?"":"same");
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+    }
+    if (str.Contains("PROFY", TString::kIgnoreCase) && fDimension==2)
+    {
+        TProfile *p = ((TH2*)fHist)->ProfileY("_pfy", -1, 9999, "s");
+        p->SetLineColor(kBlue);
+        p->Draw(only?"":"same");
+        p->SetBit(kCanDelete);
+        p->SetDirectory(NULL);
+    }
+
+    if (fHist->TestBit(kIsLogx)) pad->SetLogx();
+    if (fHist->TestBit(kIsLogy)) pad->SetLogy();
+    if (fHist->TestBit(kIsLogz)) pad->SetLogz();
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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!=Form(gsDefTitle.Data(), fDimension))
+        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-8-4/MagicSoft/Mars/mhbase/MH3.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH3.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MH3.h	(revision 3781)
@@ -0,0 +1,69 @@
+#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
+{
+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)
+
+    void StreamPrimitive(ofstream &out) const;
+
+    enum {
+        kIsLogx = BIT(17),
+        kIsLogy = BIT(18),
+        kIsLogz = BIT(19)
+    };
+
+public:
+    MH3(const unsigned int dim=0);
+    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; }
+
+    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);
+
+    MParContainer *New() const;
+
+    ClassDef(MH3, 1) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHArray.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHArray.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHArray.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhbase/MHArray.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHArray.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHArray.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhbase/MHMatrix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHMatrix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHMatrix.cc	(revision 3781)
@@ -0,0 +1,1191 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <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);
+    }
+
+    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->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);
+        col = TMatrixRow(fM, i);
+
+        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
+{
+    TMatrixColumn col(fM, ncol);
+
+    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();
+
+    TMatrix m(n, fM.GetNcols());
+    TVector vold(fM.GetNcols());
+    for (int i=0; i<n; i++)
+        TMatrixRow(m, i) = vold = TMatrixRow(fM, idx[i]);
+
+    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;
+
+    TVector vold(fM.GetNcols());
+    while (oldrow<rows)
+    {
+        sum += ratio;
+
+        if (newrow<=(unsigned int)sum)
+            TMatrixRow(fM, newrow++) = vold = TMatrixRow(fM, oldrow);
+
+        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)
+{
+    TVector v(source.GetNcols());
+
+    target.ResizeTo(rows, source.GetNcols());
+    for (Int_t ir=0; ir<rows; ir++)
+        TMatrixRow(target, ir) = v = TMatrixRow(source, ir);
+}
+
+// ------------------------------------------------------------------------
+//
+// 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;
+    TVector vold(fM.GetNcols());
+    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)
+        {
+            TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+            continue;
+        }
+
+        cumulweight[indref] -= 1.;
+        if (++evtcount1 >=  nmaxevts)
+            break;
+
+        TMatrixRow(mnewtmp, evtcount1) = vold = TMatrixRow(fM, ind[ir]);
+    }
+
+    for (/*empty*/; ir<nrows; ir++)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+
+    //
+    // 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)
+    //
+    TVector vold(fM.GetNcols());
+    for (Int_t ir=0; ir<nmaxevts; ir++)
+        TMatrixRow(mnewtmp, evtcount1++) = vold = TMatrixRow(fM, ind[ir]);
+
+    for (Int_t ir=nmaxevts; ir<nrows; ir++)
+        TMatrixRow(mrest, evtcount2++) = vold = TMatrixRow(fM, ind[ir]);
+
+    //
+    // 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
+//
+Bool_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());
+    TVector tmp(fM.GetNcols());
+    for (Int_t irow = 0; irow<fNumRows; irow++)
+    {
+        const Int_t jrow = rnd.Integer(fNumRows);
+
+        v = TMatrixRow(fM, irow);
+        TMatrixRow(fM, irow) = tmp = TMatrixRow(fM, jrow);
+        TMatrixRow(fM, jrow) = v;
+    }
+
+    *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();
+    TVector vold(ncol);
+    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(vold(jcol)))
+                break;
+
+        if (jcol==ncol)
+            TMatrixRow(fM, irow++) = vold = row;
+        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-8-4/MagicSoft/Mars/mhbase/MHMatrix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHMatrix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MHMatrix.h	(revision 3781)
@@ -0,0 +1,124 @@
+#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
+
+#include <TArrayF.h>
+
+class TArrayI;
+class TArrayF;
+
+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);
+
+    Bool_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 to store events
+};
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MWeight.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MWeight.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MWeight.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhbase/MWeight.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MWeight.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/MWeight.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhbase/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhbase/Makefile	(revision 3781)
@@ -0,0 +1,60 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HBase
+
+#
+# Library name to creatre
+#
+LIB   = mhbase.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mdata
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MFillH.cc \
+           MBinning.cc \
+           MWeight.cc \
+           MH.cc \
+           MH3.cc \
+           MHArray.cc \
+           MHMatrix.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistIncl.h	(revision 3781)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/HistLinkDef.h	(revision 3781)
@@ -0,0 +1,41 @@
+#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 MHBlindPixels+;
+
+#pragma link C++ class MHStarMap+;
+#pragma link C++ class MHEnergyTime+;
+#pragma link C++ class MHEnergyTheta+;
+#pragma link C++ class MHAlphaEnergyTime+;
+#pragma link C++ class MHAlphaEnergyTheta+;
+#pragma link C++ class MHGamma+;
+#pragma link C++ class MHFlux;
+#pragma link C++ class MHEffOnTime+;
+#pragma link C++ class MHTimeDiffTime+;
+#pragma link C++ class MHTimeDiffTheta+;
+#pragma link C++ class MHThetabarTime+;
+#pragma link C++ class MHThetabarTheta+;
+#pragma link C++ class MHSigmabarTheta+;
+#pragma link C++ class MHSigmaTheta+;
+#pragma link C++ class MHSigmaPixel+;
+#pragma link C++ class MHOnSubtraction+;
+#pragma link C++ class MHFindSignificance+;
+#pragma link C++ class MHCT1Supercuts+;
+#pragma link C++ class MHSupercuts+;
+
+#pragma link C++ class MHCompProb+;
+#pragma link C++ class MHHadronness+;    
+
+#pragma link C++ class MHCamera+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.cc	(revision 3781)
@@ -0,0 +1,563 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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!
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHAlpha.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 "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);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor
+//
+MHAlpha::MHAlpha(const char *name, const char *title)
+    : fAlphaCut(12.5), fBgMean(55), fResult(0), fMatrix(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHAlpha";
+    fTitle = title ? title : "Alpha plot";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetName("Alpha");
+    fHist.SetTitle("Alpha");
+    fHist.SetXTitle("|\\alpha| [\\circ]");
+    fHist.SetYTitle("Counts");
+    fHist.UseCurrentStyle();
+
+    MBinning binsa;
+    binsa.SetEdges(18, 0, 90);
+    binsa.Apply(fHist);
+
+    fSigInt=15;
+    fSigMax=75;
+    fBgMin=45;
+    fBgMax=90;
+    fPolynom=1;
+}
+
+// --------------------------------------------------------------------------
+//
+// Calculate Significance as
+// significance = (s-b)/sqrt(s+k*k*b) mit k=s/b
+// 
+Double_t MHAlpha::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);
+}
+
+Bool_t MHAlpha::SetupFill(const MParList *pl)
+{
+    fHist.Reset();
+
+    fResult = (MParameterD*)pl->FindObject("Significance", "MParameterD");
+    if (!fResult)
+        *fLog << warn << "Significance [MParameterD] not found... ignored." << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    if (fMatrix)
+        alpha = (*fMatrix)[fMap];
+    else
+    {
+        const MHillasSrc *hil = dynamic_cast<const MHillasSrc*>(par);
+        if (!par)
+            return kFALSE;
+
+        alpha = hil->GetAlpha();
+    }
+
+    fHist.Fill(TMath::Abs(alpha), w);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Update the projections
+//
+void MHAlpha::Paint(Option_t *opt)
+{
+    Float_t sigint=fSigInt;
+    Float_t sigmax=fSigMax;
+    Float_t bgmin =fBgMin;
+    Float_t bgmax =fBgMax;
+    Byte_t polynom=fPolynom;
+
+    // Implementing the function yourself is only about 5% faster
+    TF1 func("", Form("gaus(0) + pol%d(3)", polynom), 0, 90);
+    //TF1 func("", Form("[0]*(TMath::Gaus(x, [1], [2])+TMath::Gaus(x, -[1], [2]))+pol%d(3)", polynom), 0, 90);
+    TArrayD maxpar(func.GetNpar());
+
+    func.FixParameter(1, 0);
+    func.FixParameter(4, 0);
+    func.SetParLimits(2, 0, 90);
+    func.SetParLimits(3, -1, 1);
+
+    TH1 *h=&fHist;
+    //const Double_t alpha0 = h->GetBinContent(1);
+    //const Double_t alphaw = h->GetXaxis()->GetBinWidth(1);
+
+    // Check for the regios which is not filled...
+    const Double_t alpha0 = h->GetBinContent(1);
+    if (alpha0==0)
+        return;
+
+    // First fit a polynom in the off region
+    func.FixParameter(0, 0);
+    func.FixParameter(2, 1);
+    func.ReleaseParameter(3);
+
+    for (int i=5; i<func.GetNpar(); i++)
+        func.ReleaseParameter(i);
+
+    //h->Fit(&func, "N0Q", "", bgmin, bgmax);
+    h->Fit(&func, "N0Q", "", bgmin, bgmax);
+    func.SetRange(0, 90);
+    func.SetLineColor(kRed);
+    func.Paint("same");
+
+    //h4a.Fill(func.GetChisquare());
+    //h5a.Fill(func.GetProb());
+
+    func.ReleaseParameter(0);
+    //func.ReleaseParameter(1);
+    func.ReleaseParameter(2);
+    func.FixParameter(3, func.GetParameter(3));
+    for (int i=5; i<func.GetNpar(); i++)
+        func.FixParameter(i, func.GetParameter(i));
+
+    // Do not allow signals smaller than the background
+    const Double_t A  = alpha0-func.GetParameter(3);
+    const Double_t dA = TMath::Abs(A);
+    func.SetParLimits(0, -dA*4, dA*4);
+    func.SetParLimits(2, 0, 90);
+
+    // Now fit a gaus in the on region on top of the polynom
+    func.SetParameter(0, A);
+    func.SetParameter(2, sigmax*0.75);
+
+    //h->Fit(&func, "N0Q", "", 0, sigmax);
+    h->Fit(&func, "N0Q", "", 0, sigmax);
+    func.SetLineColor(kGreen);
+    func.Paint("same");
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHAlpha::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    fHist.Draw();
+
+    AppendPad("");
+}
+
+// --------------------------------------------------------------------------
+//
+// 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.
+//
+Bool_t MHAlpha::Finalize()
+{
+    //*fLog << dbg << "Fitting..." << endl;
+
+    Float_t sigint=fSigInt;
+    Float_t sigmax=fSigMax;
+    Float_t bgmin=fBgMin;
+    Float_t bgmax=fBgMax;
+    Byte_t polynom=fPolynom;
+
+    //                      xmin, xmax, npar
+    //TF1 func("MyFunc", fcn, 0, 90, 6);
+    // Implementing the function yourself is only about 5% faster
+    TF1 func("", Form("gaus(0) + pol%d(3)", polynom), 0, 90);
+    TArrayD maxpar(func.GetNpar());
+
+    //*fLog << "Setup pars..." << endl;
+
+    func.FixParameter(1, 0);
+    func.FixParameter(4, 0);
+    func.SetParLimits(2, 0, 90);
+    func.SetParLimits(3, -1, 1);
+
+    //    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 *h=&fHist;
+    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)
+    {
+        *fLog << warn << "Histogram empty." << endl;
+        return kTRUE;
+    }
+
+    // First fit a polynom in the off region
+    func.FixParameter(0, 0);
+    func.FixParameter(2, 1);
+    func.ReleaseParameter(3);
+
+    //*fLog << "Release pars..." << endl;
+
+    for (int i=5; i<func.GetNpar(); i++)
+        func.ReleaseParameter(i);
+
+    //*fLog << dbg << "Fit 1" << endl;
+    //h->Fit(&func, "N0Q", "", bgmin, bgmax);
+    h->Fit(&func, "N0Q", "", bgmin, bgmax);
+    //*fLog << dbg << ix << "/" << iy << ":  " << func.GetParameter(3) << "    " << func.GetParameter(4) << endl;
+
+    //h4a.Fill(func.GetChisquare());
+    //h5a.Fill(func.GetProb());
+
+    //func.SetParLimits(0, 0.5*h->GetBinContent(1), 1.5*h->GetBinContent(1));
+    //func.SetParLimits(2, 5, 90);
+
+    //*fLog << dbg << "Change params..." << endl;
+
+    func.ReleaseParameter(0);
+    //func.ReleaseParameter(1);
+    func.ReleaseParameter(2);
+    func.FixParameter(3, func.GetParameter(3));
+    for (int i=5; i<func.GetNpar(); i++)
+        func.FixParameter(i, func.GetParameter(i));
+
+    // Do not allow signals smaller than the background
+    const Double_t A  = alpha0-func.GetParameter(3);
+    const Double_t dA = TMath::Abs(A);
+    func.SetParLimits(0, -dA*4, dA*4);
+    func.SetParLimits(2, 0, 90);
+
+    // Now fit a gaus in the on region on top of the polynom
+    func.SetParameter(0, A);
+    func.SetParameter(2, sigmax*0.75);
+
+    //*fLog << dbg << "Fit 2..." << endl;
+    //h->Fit(&func, "N0Q", "", 0, sigmax);
+    h->Fit(&func, "N0Q", "", 0, sigmax);
+    //*fLog << dbg << "     " << func.GetParameter(0) << "    " << func.GetParameter(1) << "    " << func.GetParameter(2) << endl;
+
+    //*fLog << dbg << "Copy par..." << endl;
+    TArrayD p(func.GetNpar(), func.GetParameters());
+
+    // Fill results into some histograms
+    /*
+    h0a.Fill(p[0]);
+    h0b.Fill(p[3]);
+    h1.Fill(p[1]);
+    h2.Fill(p[2]);
+    if (polynom>1)
+        h3.Fill(p[5]);
+    h4b.Fill(func.GetChisquare());
+    //h5b.Fill(func.GetProb());
+    */
+    // Implementing the integral as analytical function
+    // gives the same result in the order of 10e-5
+    // and it is not faster at all...
+
+    //*fLog << dbg << "Int1 par..." << endl;
+    const Double_t s = func.Integral(0, sigint)/alphaw;
+
+    func.SetParameter(0, 0);
+    //func.SetParameter(2, 1);
+
+    //*fLog << dbg << "Int2 par..." << endl;
+    const Double_t b   = func.Integral(0, sigint)/alphaw;
+    const Double_t sig = Significance(s, b);
+
+    //*fLog << dbg << "Set Val "<<sig<<" ..." << fResult << endl;
+    if (fResult)
+        fResult->SetVal(sig);
+
+    *fLog << inf << "Found Significance: " << sig << "  (width=";
+    *fLog << func.GetParameter(2) << "°, excess=" << s-b << ")" << endl;
+
+    //*fLog << dbg << "Done." << endl;
+    return kTRUE;
+    /*
+    if (sig!=0)
+        h6.Fill(sig);
+
+    if (sig<maxs)
+    {
+        maxs = sig;
+        maxx = ix;
+        maxy = iy;
+        maxpar = p;
+        }
+       */
+/*
+
+    *fLog << inf << "done." << endl;
+
+    h0a.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+    h0b.GetXaxis()->SetRangeUser(0, maxalpha0*1.5);
+
+    //hists->SetMinimum(GetMinimumGT(*hists));
+    histb->SetMinimum(GetMinimumGT(*histb));
+
+//    clk.Stop();
+//    clk.Print();
+    TCanvas *c=new TCanvas;
+
+    c->Divide(3,2, 0, 0);
+    c->cd(1);
+    gPad->SetBorderMode(0);
+    hists->Draw("colz");
+    hists->SetBit(kCanDelete);
+    c->cd(2);
+    gPad->SetBorderMode(0);
+    hist->Draw("colz");
+    hist->SetBit(kCanDelete);
+    c->cd(3);
+    gPad->SetBorderMode(0);
+    histb->Draw("colz");
+    histb->SetBit(kCanDelete);
+    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 (\\sigma_{max}=%.1f) ",
+                                 fHist.GetXaxis()->GetBinCenter(maxx),
+                                 fHist.GetYaxis()->GetBinCenter(maxy), maxs);
+
+        TH1 *result = fHist.ProjectionZ("AlphaFit", maxx, maxx, maxy, maxy);
+        result->SetDirectory(NULL);
+        result->SetNameTitle("Result \\alpha", title);
+        result->SetBit(kCanDelete);
+        result->SetXTitle("\\alpha [\\circ]");
+        result->SetYTitle("Counts");
+        result->Draw();
+
+        TF1 f1("", func.GetExpFormula(), 0, 90);
+        TF1 f2("", func.GetExpFormula(), 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", maxpar[5]))->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);
+            const Double_t b = f2.Integral(0, (float)i);
+
+            const Double_t sig = Significance(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("\\sigma_{max}=%.1f at \\alpha_{max}=%d\\circ", maxsig, max));
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+    }*/
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHAlpha::InitMapping(MHMatrix *mat)
+{
+    if (fMatrix)
+        return;
+
+    fMatrix = mat;
+
+    fMap = fMatrix->AddColumn("MHillasSrc.fAlpha");
+}
+
+void MHAlpha::StopMapping()
+{
+    fMatrix = NULL; 
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlpha.h	(revision 3781)
@@ -0,0 +1,53 @@
+#ifndef MARS_MHAlpha
+#define MARS_MHAlpha
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MParList;
+class MParameterD;
+class MHMatrix;
+
+class MHAlpha : public MH
+{
+private:
+    Float_t fAlphaCut;        // Alpha cut
+    Float_t fBgMean;          // Background mean
+
+    Float_t fSigInt;
+    Float_t fSigMax;
+    Float_t fBgMin;
+    Float_t fBgMax;
+    Int_t   fPolynom;
+
+    TH1D    fHist;            // Alpha vs. x and y
+
+    MParameterD *fResult;
+
+    MHMatrix *fMatrix;        //!
+    Int_t fMap;               //!
+
+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();
+
+    void Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    void InitMapping(MHMatrix *mat);
+    void StopMapping();
+
+    static Double_t Significance(Double_t s, Double_t b);
+
+    ClassDef(MHAlpha, 1) // Alpha-Plot which is fitted online
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTheta.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHAlphaEnergyTime.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHBlindPixels.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHBlindPixels.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHBlindPixels.cc	(revision 3781)
@@ -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/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MHBlindPixels
+//
+////////////////////////////////////////////////////////////////////////////
+#include "MHBlindPixels.h" 
+
+#include <TCanvas.h>
+
+#include "MMcEvt.hxx"
+#include "MBlindPixels.h"
+#include "MGeomCam.h"
+#include "MPedPhotCam.h"
+#include "MParList.h"
+#include "MBinning.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHBlindPixels);
+
+using namespace std;
+
+// -------------------------------------------------------------------------
+//
+//  Default Constructor.
+//
+MHBlindPixels::MHBlindPixels(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHBlindPixels";
+    fTitle = title ? title : "Histogram for Blind Pixels vs. Theta";
+
+    //  - we initialize the histogram
+    //  - we have to give different names for the different histograms because
+    //    root don't allow us to have diferent histograms with the same name
+
+    fBlindId.SetName("2D-IdBlindPixels");
+    fBlindId.SetTitle("2D-IdBlindPixels");
+    fBlindId.SetDirectory(NULL);
+    fBlindId.SetXTitle("\\Theta [\\circ]");
+    fBlindId.SetYTitle("pixel Id");
+
+    fBlindN.SetName("2D-NBlindPixels");
+    fBlindN.SetTitle("2D-NBlindPixels");
+    fBlindN.SetDirectory(NULL);
+    fBlindN.SetXTitle("\\Theta [\\circ]");
+    fBlindN.SetYTitle("number of blind pixels");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHBlindPixels::SetupFill(const MParList *plist)
+{
+    MGeomCam *fCam = (MGeomCam*)plist->FindObject(AddSerialNumber("MGeomCam"));
+    if (!fCam)    
+    {
+        *fLog << err << "MHBlindPixels::SetupFill; MGeomCam not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << "MMcEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    
+    fPedPhot = (MPedPhotCam*)plist->FindObject("MPedPhotCam");
+    if (!fPedPhot)
+    {
+        *fLog << err << "MPedPhotCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPedPhot->InitSize(fCam->GetNumPixels());
+    
+
+    // Get Theta Binning
+    MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta", "MBinning");
+    if (!binstheta)
+    {
+        *fLog << err << "Object 'BinningTheta' [MBinning] not found... aborting" << endl;
+        return kFALSE;
+    }
+
+    // Get binning for pixel number
+    const UInt_t npix1 = fPedPhot->GetSize()+1;
+
+    MBinning binspix("BinningPixel");
+    binspix.SetEdges(npix1, -0.5, npix1-0.5);
+
+    // Set binnings in histograms
+    SetBinning(&fBlindId, binstheta, &binspix);
+    SetBinning(&fBlindN,  binstheta, &binspix);
+
+    return kTRUE;
+}
+
+// ------------------------------------------------------------------------
+// 
+// Drawing function. It creates its own canvas.
+//
+void MHBlindPixels::Draw(Option_t *option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    TH1D *h;
+
+    pad->cd(1);
+    fBlindId.Draw(option);
+
+    pad->cd(2);
+    fBlindN.Draw(option);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)&fBlindId)->ProjectionY("ProjY-pixId", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of blind pixel Id");
+    h->SetXTitle("Id of blind pixel");
+    h->SetYTitle("No. of events");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    h = ((TH2*)&fBlindN)->ProjectionY("ProjY-pixN", -1, 9999, "");
+    h->SetDirectory(NULL);
+    h->SetTitle("Distribution of no.of blind pixels");
+    h->SetXTitle("No. of blind pixels");
+    h->SetYTitle("No. of events");
+    h->Draw(option);
+    h->SetBit(kCanDelete);
+
+    pad->Modified();
+    pad->Update();
+}
+
+Bool_t MHBlindPixels::Fill(const MParContainer *par, const Stat_t w)
+{
+    if (!par)
+        return kFALSE;
+
+    Double_t theta = fMcEvt->GetTelescopeTheta()*kRad2Deg;
+    const MBlindPixels &bp = *(MBlindPixels*)par;
+
+    // FIXME: Slow.
+    const UInt_t npix = fPedPhot->GetSize();
+
+    UInt_t nb = 0;
+    for (UInt_t i=0; i<npix; i++)
+    {
+        if (bp.IsBlind(i))
+	{
+          fBlindId.Fill(theta, i, w);
+          nb++;
+	}   
+    }
+    fBlindN.Fill(theta, nb, w);
+
+    return kTRUE;
+}
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHBlindPixels.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHBlindPixels.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHBlindPixels.h	(revision 3781)
@@ -0,0 +1,47 @@
+#ifndef MARS_MHBlindPixels
+#define MARS_MHBlindPixels
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MPedPhotCam;
+class MMcEvt;
+class MParList;
+class MGeomCam;
+
+class MHBlindPixels : public MH
+{
+private:
+    MGeomCam      *fCam;      //!
+    MPedPhotCam   *fPedPhot;  //!
+    MMcEvt        *fMcEvt;    //!
+
+    TH2D          fBlindId; // 2D-histogram : pixel Id vs. Theta
+    TH2D          fBlindN;  // 2D-histogram : no.of blind pixels vs. Theta
+
+public:
+    MHBlindPixels(const char *name=NULL, const char *title=NULL);
+
+    const TH2D *GetBlindId()       { return &fBlindId; }
+    const TH2D *GetBlindId() const { return &fBlindId; }
+
+    const TH2D *GetBlindN()       { return &fBlindN; }
+    const TH2D *GetBlindN() const { return &fBlindN; }
+
+    TH2 *GetBlinIdByName(const TString name) { return &fBlindId; }
+    TH2 *GetBlinNByName(const TString name) { return &fBlindN; }
+
+    void Draw(Option_t* option = "");
+    Bool_t SetupFill(const MParList *plist);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+
+    ClassDef(MHBlindPixels, 1)  // Histogram of blind pixel Id vs. Theta
+};
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCT1Supercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCamEvent.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamEvent.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamEvent.cc	(revision 3781)
@@ -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/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
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHCamEvent.h"
+
+#include <TCanvas.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MCamEvent.h"
+#include "MHCamera.h"
+
+#include "MGeomCam.h"
+
+ClassImp(MHCamEvent);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize the name and title of the task.
+// Resets the sum histogram
+//
+MHCamEvent::MHCamEvent(const char *name, const char *title)
+    : fSum(NULL), fRms(NULL), fEvt(NULL), fType(0)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHCamEvent";
+    fTitle = title ? title : "Average of MCamEvents";
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the corresponding camera display if available
+//
+MHCamEvent::~MHCamEvent()
+{
+    if (fSum)
+        delete fSum;
+    if (fRms)
+        delete fRms;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 << warn << GetDescriptor() << ": No MCamEvent available..." << endl;
+    }
+
+    MGeomCam *cam = (MGeomCam*)plist->FindObject("MGeomCam");
+    if (!cam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found." << endl;
+        return kFALSE;
+    }
+
+    if (fSum)
+        delete (fSum);
+    if (fRms)
+        delete (fRms);
+
+    const TString name = fNameEvt.IsNull() ? fName : fNameEvt;
+
+    fSum = new MHCamera(*cam, name+";avg", fTitle);
+    fSum->SetYTitle("a.u.");
+    fSum->SetBit(MHCamera::kProfile);
+    if(TestBit(MHCamera::kVariance))
+      fSum->SetBit(MHCamera::kVariance);
+
+    fRms = new MHCamera(*cam, name+";rms", fTitle);
+    fRms->SetYTitle("a.u.");
+
+    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;
+    }
+    fSum->AddCamContent(*evt, fType);
+    fRms->SetCamContent(*fSum, 1);
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Scale the sum container with the number of entries
+//
+Bool_t MHCamEvent::Finalize()
+{
+    //fRms->AddCamContent(*fSum, 1);
+    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)
+{
+//    name.ToLower();
+
+    if (name=="sum")
+        return fSum;
+    if (name=="rms")
+        return fRms;
+
+    return NULL;
+}
+
+void MHCamEvent::Draw(Option_t *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(1,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fSum->Draw("EPhist");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    gPad->Divide(2, 1);
+    pad = gPad;
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fSum->Draw();
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fRms->Draw();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamEvent.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamEvent.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamEvent.h	(revision 3781)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHCamEvent
+#define MARS_MHCamEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MCamEvent;
+
+class MHCamEvent : public MH
+{
+private:
+    MHCamera  *fSum; // storing the sum
+    MHCamera  *fRms; // storing the rms
+    MCamEvent *fEvt; //! the current event
+
+    TString fNameEvt;
+
+    Int_t fType;
+
+    Bool_t SetupFill(const MParList *pList);
+    Bool_t Fill(const MParContainer *par, const Stat_t w=1);
+    Bool_t Finalize();
+
+public:
+    MHCamEvent(const char *name=NULL, const char *title=NULL);
+    ~MHCamEvent();
+
+    void SetNameEvt(const TString name) { fNameEvt = name; }
+    void SetType(Int_t type) { fType = type; }
+
+    TH1 *GetHistByName(const TString name="");
+
+    void Draw(Option_t *o="");
+
+    void PrintOutliers(Float_t s) const;
+
+    ClassDef(MHCamEvent, 1) // Histogram to sum camera events
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.cc	(revision 3781)
@@ -0,0 +1,1512 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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.
+//
+// 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 "MLog.h"
+#include "MLogManip.h"
+
+#include "MH.h"
+#include "MHexagon.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCamEvent.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);
+
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,01,06)
+    SetPalette(1, 0);
+#else
+    SetInvDeepBlueSeaPalette();
+#endif
+}
+
+// ------------------------------------------------------------------------
+//
+//  Default Constructor. To be used by the root system ONLY.
+//
+MHCamera::MHCamera() : TH1D(), fGeomCam(NULL), fColors(kItemsLegend)
+{
+    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)
+{
+    //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);
+}
+
+// ------------------------------------------------------------------------
+//
+// 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);
+   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);
+   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;
+}
+
+// ------------------------------------------------------------------------
+//
+// 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))
+        {
+            mean += fArray[i+1];
+            n++;
+        }
+    }
+
+    return n==0 ? 0 : Profile(mean/n);
+}
+
+// ------------------------------------------------------------------------
+//
+// Return the 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))
+        {
+            sum += fArray[i+1];
+            sq  += fArray[i+1]*fArray[i+1];
+            n++;
+        }
+    }
+
+    if (n==0)
+        return 0;
+
+    sum /= n;
+    sq  /= n;
+
+    return Profile(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 idx=0; idx<fNcells-2; idx++)
+        if (MatchSector(idx, sector, aidx) && (all || IsUsed(idx)) && fArray[idx+1]<minimum)
+            minimum = fArray[idx+1];
+
+    return Profile(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 idx=0; idx<fNcells-2; idx++)
+        if (MatchSector(idx, sector, aidx) && (all || IsUsed(idx)) && fArray[idx+1]>maximum)
+            maximum = fArray[idx+1];
+
+    return Profile(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
+        //
+        pad->Divide(1, 1, 0, 0, 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 = 50;
+
+    // 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)
+    {
+        Double_t min = GetMinimumSectors(sector, aidx);
+        Double_t max = GetMaximumSectors(sector, aidx);
+
+        Int_t newbins=0;
+
+        THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+
+        h1 = new TH1D(pname, GetTitle(), nbins, min, max);
+        h1->SetDirectory(pname.IsNull() ? NULL : gROOT);
+        h1->SetXTitle(GetYaxis()->GetTitle());
+        h1->SetYTitle("Counts");
+        //h1->Sumw2();
+    }
+
+    // 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)
+    {
+      
+      Double_t min = 0.;
+      Double_t max = fGeomCam->GetMaxRadius();
+      
+      Int_t newbins=0;
+      
+      THLimitsFinder::OptimizeLimits(nbins, newbins, min, max, kFALSE);
+      
+      h1 = new TProfile(pname, GetTitle(), nbins, min, max);
+      h1->SetDirectory(pname.IsNull() ? NULL : gROOT);
+      h1->SetXTitle("Radius from camera center [mm]");
+      h1->SetYTitle(GetYaxis()->GetTitle());
+    }
+  
+  // 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;
+}
+
+
+// ------------------------------------------------------------------------
+//
+// 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)
+        {
+            if (IsUsed(i) && iscol)
+            {
+                if (TMath::IsNaN(fArray[i+1]))
+                    gLog << warn << "MHCamera::Update: " << GetName() << " <" << GetTitle() << "> - Pixel Index #" << i << " contents is NaN (Not a Number)..." << endl;
+
+                hex.SetFillColor(GetColor(GetBinContent(i+1), min, max, islog));
+            }
+            else
+                hex.SetFillColor(10);
+        }
+
+        const MGeomPix &pix = (*fGeomCam)[i];
+
+        const Float_t x = pix.GetX()*conv;
+        const Float_t y = pix.GetY()*conv;
+        const 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);
+}
+
+
+void MHCamera::SetPrettyPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(1, 0);
+}
+
+void MHCamera::SetDeepBlueSeaPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(51, 0);
+}
+
+void MHCamera::SetInvDeepBlueSeaPalette()
+{
+    if (!TString(GetDrawOption()).Contains("hist", TString::kIgnoreCase))
+        SetPalette(52, 0);
+}
+
+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::GetBinError(Int_t bin) const
+{
+    Double_t rc = 0;
+    if (TestBit(kVariance) && GetEntries()>0) // error on the mean
+    {
+        const Double_t error = fSumw2.fArray[bin]/GetEntries();
+        const Double_t val   = fArray[bin]/GetEntries();
+        rc = TMath::Sqrt(error - val*val);
+    }
+    else
+      {
+        rc = TH1D::GetBinError(bin);
+	rc = Profile(rc);
+      }
+
+    return 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, const_cast<TArrayD&>(event)[idx]); // FIXME: Slow!
+
+        if (!used || (*const_cast<TArrayC*>(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
+//
+void MHCamera::CntCamContent(const MCamEvent &event, Double_t threshold, Int_t type)
+{
+    if (fNcells<=1 || IsFreezed())
+        return;
+
+    // FIXME: Security check missing!
+    for (Int_t idx=0; idx<fNcells-2; idx++)
+    {
+        Double_t val=threshold;
+        if (event.GetPixelContent(val, idx, *fGeomCam, type)/* && !IsUsed(idx)*/)
+            SetUsed(idx);
+
+        if (val>threshold)
+            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 (const_cast<TArrayD&>(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 += (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 Index: %d (Hardware Id=%d)", idx, idx+1);
+    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() << ">" << 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") << ">" << 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");
+} 
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCamera.h	(revision 3781)
@@ -0,0 +1,409 @@
+#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_TClonesArray
+#include <TClonesArray.h>
+#endif
+#ifndef ROOT_TH1
+#include <TH1.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),
+        kVariance = BIT(21)
+    };
+private:
+    MGeomCam      *fGeomCam;     // pointer to camera geometry (y-axis)
+    TArrayC        fUsed;        // array containing flags
+
+    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
+
+    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   SetUsed(Int_t idx)      { SETBIT(fUsed[idx], kIsUsed); }
+    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(Axis_t x, Stat_t w);
+    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); }
+
+    Int_t Fill(Axis_t x, Axis_t y, 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     SetCamContent(const MCamEvent &evt, Int_t type=0) { Reset(); AddCamContent(evt, type); }
+    virtual void     SetCamContent(const TArrayD &evt, const TArrayC *used=NULL) { Reset(); AddCamContent(evt, used); }
+    virtual void     SetCamContent(const MHCamera &d, Int_t type=0) { Reset(); AddCamContent(d, type); fEntries=d.fEntries; }
+
+    virtual void     SetCamError(const MCamEvent &evt, Int_t type=0);
+
+    virtual void     CntCamContent(const MCamEvent &evt, Double_t threshold, Int_t type=0);
+    virtual void     CntCamContent(const TArrayD &evt, Double_t threshold, Bool_t ispos=kTRUE);
+
+    Stat_t   GetBinContent(Int_t bin) const { return Profile(TH1D::GetBinContent(bin)); }
+    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() const { return GetMinimumSectors(TArrayI(), TArrayI(), kFALSE); }
+    Double_t GetMaximum() const { return GetMaximumSectors(TArrayI(), TArrayI(), kFALSE); }
+
+    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     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     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 { return ProjectionS(TArrayI(), TArrayI(), name); }
+    TH1D    *ProjectionS(Int_t sector, Int_t aidx, const char *name="_py") const
+    {
+        return ProjectionS(TArrayI(1, &sector), TArrayI(1, &aidx), name);
+    }
+    TH1D    *ProjectionS(const TArrayI &sector, const TArrayI &aidx, const char *name="_py") const;
+
+    TProfile *RadialProfile(const char *name="_rad") const { return  RadialProfileS(TArrayI(), TArrayI(), name);}
+    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;
+    
+    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-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCerPhotEvt.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCompProb.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCompProb.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCompProb.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCompProb.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCompProb.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCompProb.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCurrents.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCurrents.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCurrents.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHCurrents.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCurrents.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHCurrents.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHEffOnTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTime.cc	(revision 3781)
@@ -0,0 +1,397 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHEffOnTime                                                             //
+//                                                                          //
+//  calculates the effective on time for each bin in the variable Var       //
+//             (Var may be time or Theta)                                   //
+//                                                                          //
+//  Important : The sample of events used for this should be as close       //
+//              to the sample of recorded events as possible.               //
+//              This means that NO additional cuts (be it quality cuts or   //
+//              gamma/hadron cuts) should be applied (see MAGIC-TDAS 02-02).//
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHEffOnTime.h"
+
+#include <TStyle.h>
+
+#include <TMinuit.h>
+#include <TFitter.h>
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHTimeDiffTheta.h"
+
+ClassImp(MHEffOnTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets the name of the variable ("Time" or "Theta")
+//                      and the units of the variable ("[s]" or "[\\circ])")
+//
+MHEffOnTime::MHEffOnTime(const char *varname, const char *unit)
+    : fHEffOn(), fHProb(), fHLambda(), fHRdead()
+{
+    fVarname  = varname;
+    fUnit     = unit;
+
+    TString strg = fVarname + " " + fUnit;
+
+    //
+    //   set the name and title of this object
+    //
+    fName  = TString("MHEffOnTime-")+fVarname;
+    fTitle = "1-D histogram of Eff On Time";
+
+    // effective on time versus Var
+    fHEffOn.SetName("EffOn");
+    fHEffOn.SetTitle(TString("T_{on, eff} vs. ")+fVarname);
+
+    fHEffOn.SetDirectory(NULL);
+
+    fHEffOn.SetXTitle(strg);
+    fHEffOn.SetYTitle("T_{on, eff} [s]");
+
+    // chi2-probability versus Var
+    fHProb.SetName("Chi2-prob");
+    TString strg3("\\chi^{2}-prob of OnTimeFit vs. ");
+    strg3 += fVarname;
+    fHProb.SetTitle(strg3);
+
+    fHProb.SetDirectory(NULL);
+
+    fHProb.SetXTitle(strg);
+    fHProb.SetYTitle("\\chi^{2}-probability");
+
+    // lambda versus Var
+    fHLambda.SetName("lambda");
+    fHLambda.SetTitle(TString("\\lambda from OnTimeFit vs. ")+fVarname);
+
+    fHLambda.SetDirectory(NULL);
+
+    fHLambda.SetXTitle(strg);
+    fHLambda.SetYTitle("\\lambda [Hz]");
+
+    // Rdead versus Var
+    // Rdead is the fraction from real time lost by the dead time
+    fHRdead.SetName("Rdead");
+
+    fHRdead.SetTitle(TString("Rdead of OnTimeFit vs. ")+fVarname);
+
+    fHRdead.SetDirectory(NULL);
+
+    fHRdead.SetXTitle(strg);
+    fHRdead.SetYTitle("Rdead");
+
+}
+
+// --------------------------------------------------------------------
+//
+//  determine range (yq[0], yq[1]) of time differences
+//  where fit should be performed;
+//  require a fraction >=min of all entries to lie below yq[0]
+//      and a fraction <=max of all entries to lie below yq[1];
+//  within the range (yq[0], yq[1]) there must be no empty bin;
+//
+void MHEffOnTime::GetQuantiles(const TH1 &h, Double_t min, Double_t max, Double_t yq[2]) const
+{
+#if ROOT_VERSION_CODE < ROOT_VERSION(3,02,07)
+    // WOrkaround for missing const qualifier of TH1::Integral
+    TH1 &h1 = (TH1&)h;
+
+    // choose pedestrian approach as long as GetQuantiles is
+    // not available
+    const Int_t    jbins = h1.GetNbinsX();
+    const Double_t Nm    = h1.Integral();
+
+    const Double_t xq[2] = { 0.15*Nm, 0.98*Nm };
+
+    yq[0] = yq[1] = h1.GetBinLowEdge(jbins+1);
+
+    for (int j=1; j<=jbins; j++)
+        if (h1.Integral(2, j) >= xq[0])
+        {
+            yq[0] = h1.GetBinLowEdge(j);
+            break;
+        }
+
+    for (int j=1; j<=jbins; j++)
+        if (h1.Integral(1, j) >= xq[1] || h1.GetBinContent(j)==0)
+        {
+            yq[1] = h1.GetBinLowEdge(j);
+            break;
+        }
+#else
+    // GetQuantiles doesn't seem to be available in root 3.01/06
+    Double_t xq[2] = { min, max };
+    ((TH1&)h).GetQuantiles(2, yq, xq);
+#endif
+}
+
+void MHEffOnTime::DrawBin(TH1 &h, Int_t i) const
+{
+    TString strg1 = fVarname+"-bin #";
+    strg1 += i;
+
+    new TCanvas(strg1, strg1);
+
+    gPad->SetLogy();
+    gStyle->SetOptFit(1011);
+
+    TString name="Bin_";
+    name += i;
+
+    h.SetName(name);
+    h.SetXTitle("\\Delta t [s]");
+    h.SetYTitle("Counts");
+    h.DrawCopy();
+}
+
+Bool_t MHEffOnTime::CalcResults(const TF1 &func, Double_t Nm, Int_t i)
+{
+    const Double_t lambda = func.GetParameter(0);
+    const Double_t N0     = func.GetParameter(1);
+    const Double_t prob   = func.GetProb();
+    const Int_t    NDF    = func.GetNDF();
+
+    Double_t xmin, xmax;
+    ((TF1&)func).GetRange(xmin, xmax);
+
+    *fLog << inf;
+    *fLog << "Fitted bin #" << i << " from " << xmin << " to " << xmax;
+    *fLog << ",  got: lambda=" << lambda << "Hz N0=" << N0 << endl;
+
+    if (prob<=0.01)
+    {
+        *fLog << warn << "WARN - Fit bin#" << i << " gives:";
+        *fLog << " Chi^2-Probab(" << prob << ")<0.01";
+        *fLog << " NoFitPts=" << func.GetNumberFitPoints();
+        *fLog << " Chi^2=" << func.GetChisquare();
+    }
+
+    // was fit successful ?
+    if (NDF<=0 || /*prob<=0.001 ||*/ lambda<=0 || N0<=0)
+    {
+        *fLog << warn << dbginf << "Fit failed bin #" << i << ": ";
+        if (NDF<=0)
+            *fLog << " NDF(Number of Degrees of Freedom)=0";
+        if (lambda<=0)
+            *fLog << " Parameter#0(lambda)=0";
+        if (N0<=0)
+            *fLog << " Parameter#1(N0)=0";
+        *fLog << endl;
+
+        return kFALSE;
+    }
+
+    //
+    // -------------- start error calculation ----------------
+    //
+    Double_t emat[2][2];
+    gMinuit->mnemat(&emat[0][0], 2);
+
+    //
+    // Rdead : fraction of real time lost by the dead time
+    // kappa = number of observed events (Nm) divided by
+    //         the number of genuine events (N0)
+    // Teff  : effective on-time
+    //
+    const Double_t Teff  = Nm/lambda;
+    const Double_t kappa = Nm/N0;
+    const Double_t Rdead = 1.0 - kappa;
+
+    const Double_t dldl   = emat[0][0];
+    const Double_t dN0dN0 = emat[1][1];
+
+    const Double_t dTeff = Teff * sqrt(dldl/(lambda*lambda) + 1.0/Nm);
+    const Double_t dl = sqrt(dldl);
+    const Double_t dRdead = kappa * sqrt(dN0dN0/(N0*N0) + 1.0/Nm);
+    //
+    // -------------- end error calculation ----------------
+    //
+
+    // the effective on time is Nm/lambda
+    fHEffOn.SetBinContent(i,  Teff);
+    fHEffOn.SetBinError  (i, dTeff);
+
+    // plot chi2-probability of fit
+    fHProb.SetBinContent(i, prob);
+
+    // lambda from fit
+    fHLambda.SetBinContent(i, lambda);
+    fHLambda.SetBinError  (i,     dl);
+
+    // Rdead from fit
+    fHRdead.SetBinContent(i, Rdead);
+    fHRdead.SetBinError  (i,dRdead);
+
+    return kTRUE;
+}
+
+void MHEffOnTime::ResetBin(Int_t i)
+{
+    fHEffOn.SetBinContent (i, 1.e-20);
+    fHProb.SetBinContent  (i, 1.e-20);
+    fHLambda.SetBinContent(i, 1.e-20);
+    fHRdead.SetBinContent (i, 1.e-20);
+}
+
+// -----------------------------------------------------------------------
+//
+// Calculate the effective on time by fitting the distribution of
+// time differences
+//
+void MHEffOnTime::Calc(const TH2D *hist, const Bool_t draw)
+{
+    // nbins = number of Var bins
+    const Int_t nbins = hist->GetNbinsY();
+
+    for (int i=1; i<=nbins; i++)
+    {
+        TH1D &h = *((TH2D*)hist)->ProjectionX(TString("Calc-")+fVarname,
+                                              i, i, "E");
+        if (draw)
+            DrawBin(h, i);
+
+        ResetBin(i);
+
+        // Nmdel = Nm * binwidth,  with Nm = number of observed events
+        const Double_t Nm    = h.Integral();
+        const Double_t Nmdel = h.Integral("width");
+        if (Nm <= 0)
+        {
+            *fLog << warn << dbginf << "Nm<0 for bin #" << i << endl;
+            delete &h;
+            continue;
+        }
+
+        Double_t yq[2];
+        GetQuantiles(h, 0.15, 0.95, yq);
+
+        //
+        // Setup Poisson function for the fit:
+        // lambda [Hz], N0 = ideal no of evts, del = bin width of dt
+        //
+        TF1 func("Poisson", " [1]*[2] * [0] * exp(-[0] *x)", yq[0], yq[1]);
+        func.SetParNames("lambda", "N0", "del");
+
+        func.SetParameter(0, 1);
+        func.SetParameter(1, Nm);
+        func.FixParameter(2, Nmdel/Nm);
+
+        // For me (TB) it seems that setting parameter limits isn't necessary
+
+        // For a description of the options see TH1::Fit
+        h.Fit("Poisson", "0IRQ");
+
+        // Calc and fill results of fit into the histograms
+        const Bool_t rc = CalcResults(func, Nm, i);
+
+        // draw the distribution of time differences if requested
+        if (rc && draw)
+            func.DrawCopy("same");
+
+        delete &h;
+    }
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHEffOnTime::SetupFill(const MParList *plist)
+{
+    TString bn = "Binning"+fVarname;
+
+    const MBinning* binsVar = (MBinning*)plist->FindObject(bn);
+
+    if (!binsVar)
+    {
+        *fLog << err << dbginf << bn << " [MBinning] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHEffOn,  binsVar);
+    SetBinning(&fHProb,   binsVar);
+    SetBinning(&fHLambda, binsVar);
+    SetBinning(&fHRdead,  binsVar);
+
+    fHEffOn.Sumw2();
+    fHProb.Sumw2();
+    fHLambda.Sumw2();
+    fHRdead.Sumw2();
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEffOnTime::Draw(Option_t *opt) 
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHEffOn.Draw(opt);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHProb.Draw(opt);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHLambda.Draw(opt);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHRdead.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+void MHEffOnTime::Calc(const MHTimeDiffTheta &hist, const Bool_t Draw)
+{
+    Calc(hist.GetHist(), Draw);
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTime.h	(revision 3781)
@@ -0,0 +1,48 @@
+#ifndef MARS_MHEffOnTime
+#define MARS_MHEffOnTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class TH2D;
+class MHTimeDiffTheta;
+class MParList;
+
+class MHEffOnTime : public MH
+{
+private:
+    TH1D fHEffOn;
+    TH1D fHProb;
+    TH1D fHLambda;
+    TH1D fHRdead;
+
+    TString fVarname;
+    TString fUnit;
+
+    void ResetBin(Int_t i);
+    Bool_t CalcResults(const TF1 &func, Double_t Nm, Int_t i);
+    void DrawBin(TH1 &h, Int_t i) const;
+    void GetQuantiles(const TH1 &h, Double_t min, Double_t max, Double_t yq[2]) const;
+
+public:
+    MHEffOnTime(const char *varname=NULL, const char *unit=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+
+    const TH1D *GetHist() { return &fHEffOn; }
+    const TH1D *GetHist() const { return &fHEffOn; }
+
+    void Calc(const TH2D *hist, const Bool_t Draw);
+    void Calc(const MHTimeDiffTheta &hist, const Bool_t Draw);
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHEffOnTime, 0) //1D-plot of Delta t vs. Var
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.cc	(revision 3781)
@@ -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    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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHEffOnTimeTheta                                                        //
+//                                                                          //
+//  calculates the effective on time for each bin in Theta                  //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHEffOnTimeTheta.h"
+
+#include <TStyle.h>
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEffOnTimeTheta);
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histograms. 
+//
+MHEffOnTimeTheta::MHEffOnTimeTheta(const char *name, const char *title)
+    : fHEffOn()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEffOnTimeTheta";
+    fTitle = title ? title : "1-D histogram of Eff On Time";
+
+    // effective on time versus theta
+    fHEffOn.SetName("EffOn");
+    fHEffOn.SetTitle("Effective On Time vs. Theta");
+
+    fHEffOn.SetDirectory(NULL);
+
+    fHEffOn.SetXTitle("\\Theta [\\circ]");
+    fHEffOn.SetYTitle("t_{eff} [s]");
+
+    // chi2/NDF versus theta
+    fHChi2.SetName("Chi2/NDF");
+    fHChi2.SetTitle("Chi2/NDF of OnTimeFit vs. Theta");
+
+    fHChi2.SetDirectory(NULL);
+
+    fHChi2.SetXTitle("\\Theta [\\circ]");
+    fHChi2.SetYTitle("chi^{2}/NDF");
+
+    // lambda versus theta
+    fHLambda.SetName("lambda");
+    fHLambda.SetTitle("lambda of OnTimeFit vs. Theta");
+
+    fHLambda.SetDirectory(NULL);
+
+    fHLambda.SetXTitle("\\Theta [\\circ]");
+    fHLambda.SetYTitle("\\lambda [Hz]");
+
+    // N0del versus theta
+    fHN0del.SetName("N0del");
+    fHN0del.SetTitle("N0del of OnTimeFit vs. Theta");
+
+    fHN0del.SetDirectory(NULL);
+
+    fHN0del.SetXTitle("\\Theta [\\circ]");
+    fHN0del.SetYTitle("N0del");
+}
+
+// -----------------------------------------------------------------------
+//
+// Calculate the effective on time by fitting the distribution of
+// time differences
+//
+void MHEffOnTimeTheta::Calc(TH2D *hist)
+{
+    // nbins = number of Theta bins
+    const Int_t nbins = hist->GetNbinsY();
+
+    for (int i=1; i<=nbins; i++)
+    {
+        //        TH1D &h = *hist->ProjectionX("Calc-theta", i, i);
+        TH1D &h = *hist->ProjectionX("Calc-theta", i, i, "E");
+
+        // Nmdel = Nm * binwidth,  with Nm = number of observed events
+        const Double_t Nmdel = h.Integral("width");
+        const Double_t Nm    = h.Integral();
+        //        Double_t mean  = h->GetMean();
+
+        //...................................................
+        // 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.15, 0.95 };
+        Double_t yq[2];
+
+        // GetQuantiles doesn't seem to be available in root 3.01/06
+	// h->GetQuantiles(2,yq,xq);
+
+        const Double_t sumtot = h.Integral();
+        const Int_t    jbins  = h.GetNbinsX();
+
+        if (sumtot > 0.0)
+        {
+            Double_t sum1 = 0.0;
+            yq[0] = h.GetBinLowEdge(jbins+1);
+            for (int j=1; j<=jbins; j++)
+            {
+                if (sum1 >= xq[0]*sumtot)
+                {
+                    yq[0] = h.GetBinLowEdge(j);
+                    break;
+                }
+                sum1 += h.GetBinContent(j);
+            }
+
+            Double_t sum2 = 0.0;
+            yq[1] = h.GetBinLowEdge(jbins+1);
+            for (int j=1; j<=jbins; j++)
+            {
+                Double_t content = h.GetBinContent(j);
+                sum2 += content;
+                if (sum2 >= xq[1]*sumtot || content == 0.0)
+                {
+                    yq[1] = h.GetBinLowEdge(j);
+                    break;
+                }
+            }
+
+            //...................................................
+
+            // parameter 0 = lambda
+            // parameter 1 = N0*del        with N0 = ideal number of events
+            //                             and del = bin width of time difference
+            TF1 func("Poisson", "[1] * [0] * exp(-[0] *x)", yq[0], yq[1]);
+
+            func.SetParameter(0, 100); // [Hz]
+            func.SetParameter(1, Nmdel);
+
+            func.SetParLimits(0, 0, 1000);    // [Hz]
+            func.SetParLimits(1, 0, 10*Nmdel);
+
+            func.SetParName(0, "lambda");
+            func.SetParName(1, "Nmdel");
+
+            // options : 0  do not plot the function
+            //           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("Poisson", "0IRQ");
+
+            // gPad->SetLogy();
+            // gStyle->SetOptFit(1011);
+            // h->GetXaxis()->SetTitle("time difference [s]");
+            // h->GetYaxis()->SetTitle("Counts");
+            // h->DrawCopy();
+
+            // func.SetRange(yq[0], yq[1]); // Range of Drawing
+            // func.DrawCopy("same");
+
+            const Double_t lambda = func.GetParameter(0);
+            const Double_t N0del  = func.GetParameter(1);
+            const Double_t chi2   = func.GetChisquare();
+            const Int_t    NDF    = func.GetNDF();
+
+            // was fit successful ?
+            if (NDF>0 && chi2<2.5*NDF)
+            {
+                // the effective on time is Nm/lambda
+                fHEffOn.SetBinContent(i, Nm/lambda);
+
+                // plot chi2/NDF of fit
+                fHChi2.SetBinContent(i, NDF ? chi2/NDF : 0.0);
+
+                // lambda of fit
+                fHLambda.SetBinContent(i, lambda);
+
+                // N0del of fit
+                fHN0del.SetBinContent(i, N0del);
+
+                delete &h;
+                continue;
+            }
+        }
+
+        fHEffOn.SetBinContent (i, 1.e-20);
+        fHChi2.SetBinContent  (i, 1.e-20);
+        fHLambda.SetBinContent(i, 1.e-20);
+        fHN0del.SetBinContent (i, 1.e-20);
+
+        delete &h;
+    }
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHEffOnTimeTheta::SetupFill(const MParList *plist)
+{
+   const MBinning* bins = (MBinning*)plist->FindObject("BinningTheta");
+   if (!bins)
+   {
+       *fLog << err << dbginf << "BinningTheta [MBinning] not found... aborting." << endl;
+       return kFALSE;
+   }
+
+   SetBinning(&fHEffOn,  bins);
+   SetBinning(&fHChi2,   bins);
+   SetBinning(&fHLambda, bins);
+   SetBinning(&fHN0del,  bins);
+
+   fHEffOn.Sumw2();
+   fHChi2.Sumw2();
+   fHLambda.Sumw2();
+   fHN0del.Sumw2();
+
+   return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEffOnTimeTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHEffOn.Draw(opt);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHChi2.Draw(opt);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHLambda.Draw(opt);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHN0del.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTheta.h	(revision 3781)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHEffOnTimeTheta
+#define MARS_MHEffOnTimeTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MTime;
+class TH2D;
+class MParList;
+
+class MHEffOnTimeTheta : public MH
+{
+private:
+    TH1D fHEffOn;
+    TH1D fHChi2;
+    TH1D fHN0del;
+    TH1D fHLambda;
+
+public:
+    MHEffOnTimeTheta(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+
+    const TH1D *GetHist() { return &fHEffOn; }
+    const TH1D *GetHist() const { return &fHEffOn; }
+
+    void Calc(TH2D *hist);
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHEffOnTimeTheta, 0) //1D-plot of Delta t vs. Theta
+};
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.cc	(revision 3781)
@@ -0,0 +1,298 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHEffOnTimeTime                                                         //
+//                                                                          //
+//  calculates the effective on time for each bin in time                   //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHEffOnTimeTime.h"
+
+#include <TStyle.h>
+
+#include <TF1.h>
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHEffOnTimeTime);
+
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histograms.
+//
+MHEffOnTimeTime::MHEffOnTimeTime(const char *name, const char *title)
+    : fHEffOn()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHEffOnTimeTime";
+    fTitle = title ? title : "1-D histogram of Eff On Time";
+
+    // effective on time versus time
+    fHEffOn.SetName("EffOn");
+    fHEffOn.SetTitle("Effective On Time vs. Time");
+
+    fHEffOn.SetDirectory(NULL);
+
+    fHEffOn.SetXTitle("time [s]");
+    fHEffOn.SetYTitle("t_{eff} [s]");
+
+    // chi2/NDF versus time
+    fHChi2.SetName("Chi2/NDF");
+    fHChi2.SetTitle("Chi2/NDF of OnTimeFit vs. Time");
+
+    fHChi2.SetDirectory(NULL);
+
+    fHChi2.SetXTitle("time [s]");
+    fHChi2.SetYTitle("chi^{2}/NDF");
+
+    // lambda versus time
+    fHLambda.SetName("lambda");
+    fHLambda.SetTitle("lambda of OnTimeFit vs. Time");
+
+    fHLambda.SetDirectory(NULL);
+
+    fHLambda.SetXTitle("time [s]");
+    fHLambda.SetYTitle("\\lambda [Hz]");
+
+    // N0del versus time
+    fHN0del.SetName("N0del");
+    fHN0del.SetTitle("N0del of OnTimeFit vs. Time");
+
+    fHN0del.SetDirectory(NULL);
+
+    fHN0del.SetXTitle("time [s]");
+    fHN0del.SetYTitle("N0del");
+}
+
+// -----------------------------------------------------------------------
+//
+// Calculate the effective on time by fitting the distribution of
+// time differences
+//
+void MHEffOnTimeTime::Calc(TH2D *hist)
+{
+    // nbins = number of time bins
+    const Int_t nbins = hist->GetNbinsY();
+
+    for (int i=1; i<=nbins; i++)
+    {
+
+        //        TH1D &h = *hist->ProjectionX("Calc-time", i, i, "E");
+        TH1D &h = *hist->ProjectionX("Calc-time", i, i, "E");
+
+
+        // Nmdel = Nm * binwidth,  with Nm = number of observed events
+        const Double_t Nmdel = h.Integral("width");
+        const Double_t Nm    = h.Integral();
+	//        Double_t mean  = h->GetMean();
+
+        //...................................................
+        // 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.15, 0.95 };
+        Double_t yq[2];
+
+        // GetQuantiles doesn't seem to be available in root 3.01/06
+	// h->GetQuantiles(2,yq,xq);
+
+        const Double_t sumtot = h.Integral();
+        const Int_t    jbins  = h.GetNbinsX();
+       
+        if (sumtot > 0.0)
+        {
+            // char txt[100];
+            // sprintf(txt, "time_bin:%d", i);
+            // new TCanvas(txt, txt);
+
+            Double_t sum1 = 0.0;
+            yq[0]  = h.GetBinLowEdge(jbins+1);
+            for (int j=1; j<=jbins; j++)
+            {
+                if (sum1 >= xq[0]*sumtot)
+                {
+                    yq[0] = h.GetBinLowEdge(j);
+                    break;
+                }
+                sum1 += h.GetBinContent(j);
+            }
+        
+            Double_t sum2 = 0.0;
+            yq[1] = h.GetBinLowEdge(jbins+1);
+            for (int j=1; j<=jbins; j++)
+            {
+                const Double_t content = h.GetBinContent(j);
+                sum2 += content;
+                if (sum2 >= xq[1]*sumtot || content == 0.0)
+                {
+                    yq[1] = h.GetBinLowEdge(j);
+                    break;
+                }
+            }
+
+            //...................................................
+
+            // parameter 0 = lambda
+            // parameter 1 = N0*del        with N0 = ideal number of events
+            //                             and del = bin width of time difference
+            TF1 func("Poisson", "[1] * [0] * exp(-[0] *x)", yq[0], yq[1]);
+
+            func.SetParameter(0, 100); // [Hz]
+            func.SetParameter(1, Nmdel);
+
+            func.SetParLimits(0, 0, 1000);    // [Hz]
+            func.SetParLimits(1, 0, 10*Nmdel);
+
+            func.SetParName(0, "lambda");
+            func.SetParName(1, "Nmdel");
+
+            // options : 0  (=zero) do not plot the function
+            //           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("Poisson", "0IRQ");
+
+            // gPad->SetLogy();
+            // gStyle->SetOptFit(1011);
+            // h->GetXaxis()->SetTitle("time difference [s]");
+            // h->GetYaxis()->SetTitle("Counts");
+            // h->DrawCopy();
+
+            // func.SetRange(yq[0], yq[1]); // Range of Drawing
+            // func.DrawCopy("same");
+
+            const Double_t lambda = func.GetParameter(0);
+            const Double_t N0del  = func.GetParameter(1);
+            const Double_t chi2   = func.GetChisquare();
+            const Int_t    NDF    = func.GetNDF();
+
+            // was fit successful ?
+            if (NDF>0  &&  chi2<2.5*NDF)
+            {
+                // the effective on time is Nm/lambda
+                fHEffOn.SetBinContent(i, Nm/lambda);
+
+                // plot chi2/NDF of fit
+                fHChi2.SetBinContent(i, NDF ? chi2/NDF : 0.0);
+
+                // lambda of fit
+                fHLambda.SetBinContent(i, lambda);
+
+                // N0del of fit
+                fHN0del.SetBinContent(i, N0del);
+
+                delete &h;
+                continue;
+            }
+        }
+
+        fHEffOn.SetBinContent (i, 1.e-20);
+        fHChi2.SetBinContent  (i, 1.e-20);
+        fHLambda.SetBinContent(i, 1.e-20);
+        fHN0del.SetBinContent (i, 1.e-20);
+
+        delete &h;
+    }
+}
+
+// -------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histograms
+//
+Bool_t MHEffOnTimeTime::SetupFill(const MParList *plist)
+{
+    const MBinning* binstime = (MBinning*)plist->FindObject("BinningTime");
+    if (!binstime)
+    {
+        *fLog << err << dbginf << "BinningTime [MBinning] not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHEffOn,  binstime);
+    SetBinning(&fHChi2,   binstime);
+    SetBinning(&fHLambda, binstime);
+    SetBinning(&fHN0del,  binstime);
+
+    fHEffOn.Sumw2();
+    fHChi2.Sumw2();
+    fHLambda.Sumw2();
+    fHN0del.Sumw2();
+
+    return kTRUE;
+}
+
+// -------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHEffOnTimeTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    fHEffOn.Draw(opt);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fHChi2.Draw(opt);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    fHLambda.Draw(opt);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    fHN0del.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEffOnTimeTime.h	(revision 3781)
@@ -0,0 +1,39 @@
+#ifndef MARS_MHEffOnTimeTime
+#define MARS_MHEffOnTimeTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH1
+#include <TH1.h>
+#endif
+
+class MTime;
+class TH2D;
+class MParList;
+
+class MHEffOnTimeTime : public MH
+{
+private:
+    TH1D fHEffOn;
+    TH1D fHChi2;
+    TH1D fHLambda;
+    TH1D fHN0del;
+
+public:
+    MHEffOnTimeTime(const char *name=NULL, const char *title=NULL);
+
+    Bool_t SetupFill(const MParList *pList);
+
+    const TH1D *GetHist() { return &fHEffOn; }
+    const TH1D *GetHist() const { return &fHEffOn; }
+
+    void Calc(TH2D *hist);
+
+    void Draw(Option_t *option="");
+
+    ClassDef(MHEffOnTimeTime, 0) //1D-plot of Delta t vs. time
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTheta.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHEnergyTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTime.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHEnergyTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEnergyTime.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHEvent.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEvent.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEvent.cc	(revision 3781)
@@ -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): 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 "MHCamera.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MParList.h"
+#include "MCerPhotEvt.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 kEvtRelativeSignal:
+        fHist->SetName("Signal/PedRMS");
+        fHist->SetYTitle("S/P_{rms}");
+        break;
+    case kEvtCleaningLevels:
+        if (!fImgCleanStd)
+        {
+            *fLog << err << "MImgCleanStd not found... aborting." << endl;
+            return kFALSE;
+        }
+        fHist->SetName("CleanLevels");
+        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;
+    }
+
+    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, 1);
+        break;
+    case kEvtRelativeSignal:
+        fHist->SetCamContent(*event, 0);
+        break;
+    case kEvtCleaningLevels:
+        {
+            TArrayF lvl(2);
+            lvl[0] = fImgCleanStd->GetCleanLvl2();
+            lvl[1] = fImgCleanStd->GetCleanLvl1();
+            fHist->SetCamContent(*event, 0);
+            fHist->SetLevels(lvl);
+        }
+        break;
+    case kEvtIdxMax:
+        fHist->SetCamContent(*event, 5);
+        break;
+    case kEvtArrTime:
+        fHist->SetCamContent(*event, 0);
+        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::Draw(Option_t *)
+{
+    if (!fHist)
+    {
+        *fLog << warn << "MHEvent::Draw - fHist==NULL not initialized." << endl;
+        return;
+    }
+
+    if (!gPad)
+        MakeDefCanvas(this);
+    fHist->Draw();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEvent.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEvent.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHEvent.h	(revision 3781)
@@ -0,0 +1,59 @@
+#ifndef MARS_MHEvent
+#define MARS_MHEvent
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class MHCamera;
+class MRawEvtData;
+class MRawRunHeader;
+class MRawEvtHeader;
+
+class MMcEvt;
+class MCerPhotEvt;
+class MImgCleanStd;
+class MCameraSignal;
+
+class MHEvent : public MH
+{
+public:
+    enum EventType_t {
+        kEvtSignalRaw, kEvtSignalDensity, kEvtPedestal, 
+        kEvtPedestalRMS, kEvtRelativeSignal, kEvtCleaningLevels,
+        kEvtIdxMax, kEvtArrTime 
+    };
+
+private:
+    MRawEvtData   *fRawEvtData;    //!
+    MRawRunHeader *fRawRunHeader;  //!
+    MRawEvtHeader *fRawEvtHeader;  //!
+
+    MMcEvt        *fMcEvt;         //!
+    MCerPhotEvt   *fCerPhotEvt;    //!
+    MImgCleanStd  *fImgCleanStd;   //!
+    MCameraSignal *fCamSignal;     //!
+
+    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="");
+ 
+    ClassDef(MHEvent, 1)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcCam.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHFadcCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcCam.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHFadcPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcPix.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHFadcPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFadcPix.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHFalseSource.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFalseSource.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFalseSource.cc	(revision 3781)
@@ -0,0 +1,1086 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHFalseSource.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 "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHFalseSource);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// 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), fMinLD(-1), fMaxLD(-1)
+{
+    //
+    //   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)
+{
+    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();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHFalseSource::Significance(Double_t s, Double_t b)
+{
+    return MMath::SignificanceSym(s, b);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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
+//
+Double_t MHFalseSource::SignificanceLiMa(Double_t s, Double_t b, Double_t alpha)
+{
+    return MMath::SignificanceLiMaSigned(s, b);
+    /*
+     const Double_t lima = MMath::SignificanceLiMa(s, b);
+     return lima<0 ? 0 : lima;
+     */
+}
+
+// --------------------------------------------------------------------------
+//
+// Set binnings (takes BinningFalseSource) and prepare filling of the
+// histogram.
+//
+// Also search for MTime, MObservatory and MPointingPos
+// 
+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;
+    }
+
+    fMm2Deg = geom->GetConvMm2Deg();
+
+    MBinning binsa;
+    binsa.SetEdges(18, 0, 90);
+
+    const MBinning *bins = (MBinning*)plist->FindObject("BinningFalseSource");
+    if (!bins)
+    {
+        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;
+
+    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->GetRa();
+    fDec = fPointPos->GetDec();
+
+    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;
+            src.SetXY(v);
+
+            // Source dependant hillas parameters
+            if (!hsrc.Calc(hil))
+            {
+                *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 (fMaxLD>0 && hil->GetLength()>fMaxLD*hsrc.GetDist())
+                continue;
+            if (fMinLD>0 && hil->GetLength()<fMinLD*hsrc.GetDist())
+                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(TH2D *h2, TH2D *all)
+{
+    TAxis &axe = *fHist.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*)fHist.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(TH2D *h3, TH2D *all)
+{
+    TAxis &axe = *fHist.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*)fHist.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("yx_all");
+
+    // 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));
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+
+    // 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(h3, h0);
+
+    // Update projection of off-events
+    padsave->GetPad(1)->cd(3);
+    if ((h2 = (TH2D*)gPad->FindObject("Alpha_yx_off")))
+        ProjectOff(h2, h0);
+
+    padsave->GetPad(2)->cd(2);
+    if ((h5 = (TH2D*)gPad->FindObject("Alpha_yx_diff")))
+    {
+        h5->Add(h3, h2, -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 = SignificanceLiMa(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")) && 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", maxx, maxx, maxy, maxy);
+            h->SetTitle(Form("Distribution of \\alpha for x=%.2f y=%.2f (\\sigma_{max}=%.1f)", x, y, s));
+        }
+    }
+
+    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;
+    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 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);
+    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);
+    fHist.GetZaxis()->SetRangeUser(fBgMean-fAlphaCut/2, fBgMean+fAlphaCut/2);
+    TH1 *h2 = fHist.Project3D("yx_off");
+    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);
+    gPad->SetBorderMode(0);
+    gPad->Divide(3, 1);
+
+    // PAD #4
+    pad->GetPad(2)->cd(1);
+    gPad->SetBorderMode(0);
+    TH1 *h1 = fHist.ProjectionZ("Alpha");
+    h1->SetDirectory(NULL);
+    h1->SetTitle("Distribution of \\alpha");
+    h1->SetXTitle(fHist.GetZaxis()->GetTitle());
+    h1->SetYTitle("Counts");
+    h1->Draw(opt);
+    h1->SetBit(kCanDelete);
+
+    // 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();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    //                      xmin, xmax, npar
+    //TF1 func("MyFunc", fcn, 0, 90, 6);
+    // Implementing the function yourself is only about 5% faster
+    TF1 func("", Form("gaus(0) + pol%d(3)", polynom), 0, 90);
+    //TF1 func("", Form("[0]*(TMath::Gaus(x, [1], [2])+TMath::Gaus(x, -[1], [2]))+pol%d(3)", polynom), 0, 90);
+    TArrayD maxpar(func.GetNpar());
+
+    /*  func.SetParName(0, "A");
+     *  func.SetParName(1, "mu");
+     *  func.SetParName(2, "sigma");
+    */
+
+    func.FixParameter(1, 0);
+    func.FixParameter(4, 0);
+    func.SetParLimits(2, 0, 90);
+    func.SetParLimits(3, -1, 1);
+
+    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;
+
+    TH1 *h=0;
+    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);
+
+            const Double_t alpha0 = h->GetBinContent(1);
+
+            // Check for the regios which is not filled...
+            if (alpha0==0)
+                continue;
+
+            h->Scale(entries/h->GetEntries());
+
+            if (alpha0>maxalpha0)
+                maxalpha0=alpha0;
+
+            // First fit a polynom in the off region
+            func.FixParameter(0, 0);
+            func.FixParameter(2, 1);
+            func.ReleaseParameter(3);
+
+            for (int i=5; i<func.GetNpar(); i++)
+                func.ReleaseParameter(i);
+
+            h->Fit(&func, "N0Q", "", bgmin, bgmax);
+
+            h4a.Fill(func.GetChisquare());
+            //h5a.Fill(func.GetProb());
+
+            //func.SetParLimits(0, 0.5*h->GetBinContent(1), 1.5*h->GetBinContent(1));
+            //func.SetParLimits(2, 5, 90);
+
+            func.ReleaseParameter(0);
+            //func.ReleaseParameter(1);
+            func.ReleaseParameter(2);
+            func.FixParameter(3, func.GetParameter(3));
+            for (int i=5; i<func.GetNpar(); i++)
+                func.FixParameter(i, func.GetParameter(i));
+
+            // Do not allow signals smaller than the background
+            const Double_t A  = alpha0-func.GetParameter(3);
+            const Double_t dA = TMath::Abs(A);
+            func.SetParLimits(0, -dA*4, dA*4);
+            func.SetParLimits(2, 0, 90);
+
+            // Now fit a gaus in the on region on top of the polynom
+            func.SetParameter(0, A);
+            func.SetParameter(2, sigmax*0.75);
+
+            h->Fit(&func, "N0Q", "", 0, sigmax);
+
+            TArrayD p(func.GetNpar(), func.GetParameters());
+
+            // Fill results into some histograms
+            h0a.Fill(p[0]);
+            h0b.Fill(p[3]);
+            h1.Fill(p[1]);
+            h2.Fill(p[2]);
+            if (polynom>1)
+                h3.Fill(p[5]);
+            h4b.Fill(func.GetChisquare());
+            //h5b.Fill(func.GetProb());
+
+            // Implementing the integral as analytical function
+            // gives the same result in the order of 10e-5
+            // and it is not faster at all...
+            //const Bool_t ok = /*p[0]>=0 && /*p[0]<alpha0*2 &&*/ p[2]>1.75;// && p[2]<88.5;
+            /*
+            if (p[0]<-fabs(alpha0-p[3])*7 && p[2]<alphaw/3)
+            {
+                func.SetParameter(0, alpha0-p[3]);
+                cout << p[2] << " " << p[0] << " " << alpha0-p[3] << endl;
+            }
+            */
+
+            // The fitted function returned units of
+            // counts bin binwidth. To get the correct number
+            // of events we must adapt the functions by dividing
+            // the result of the integration by the bin-width
+            const Double_t s = func.Integral(0, sigint)/w;
+
+            func.SetParameter(0, 0);
+            func.SetParameter(2, 1);
+
+            const Double_t b   = func.Integral(0, sigint)/w;
+            const Double_t sig = SignificanceLiMa(s, b);
+
+            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/* && (ix-nx/2)*(ix-nx/2)+(iy-ny/2)*(iy-ny/2)<nr*nr/9*/)
+            {
+                maxs = sig;
+                maxx = ix;
+                maxy = iy;
+                maxpar = p;
+            }
+        }
+
+    *fLog << inf << "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);
+    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 (\\sigma_{max}=%.1f) ",
+                                 hist->GetXaxis()->GetBinCenter(maxx),
+                                 hist->GetYaxis()->GetBinCenter(maxy), maxs);
+
+        TH1 *result = fHist.ProjectionZ("AlphaFit", maxx, maxx, maxy, maxy);
+        result->Scale(entries/h->GetEntries());
+
+        result->SetDirectory(NULL);
+        result->SetNameTitle("Result \\alpha", title);
+        result->SetBit(kCanDelete);
+        result->SetXTitle("\\alpha [\\circ]");
+        result->SetYTitle("Counts");
+        result->Draw();
+
+        TF1 f1("", func.GetExpFormula(), 0, 90);
+        TF1 f2("", func.GetExpFormula(), 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", maxpar[5]))->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 = SignificanceLiMa(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("\\sigma_{max}=%.1f at \\alpha_{max}=%d\\circ", maxsig, max));
+        leg->SetBit(kCanDelete);
+        leg->Draw();
+    }
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFalseSource.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFalseSource.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFalseSource.h	(revision 3781)
@@ -0,0 +1,86 @@
+#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 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
+    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 fMinLD;              // Minimum distance in percent of dist
+    Float_t fMaxLD;              // Maximum distance in percent of dist
+
+    TH3D    fHist;               // Alpha vs. x and y
+
+    Double_t fRa;
+    Double_t fDec;
+
+    Int_t DistancetoPrimitive(Int_t px, Int_t py);
+    void Modified();
+
+    void ProjectAll(TH2D *h);
+    void ProjectOff(TH2D *h, TH2D *all);
+    void ProjectOn(TH2D *h, TH2D *all);
+
+    TObject *GetCatalog();
+
+    void MakeSymmetric(TH1 *h);
+
+public:
+    MHFalseSource(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 FitSignificance(Float_t sigint=15, Float_t sigmax=70, Float_t bgmin=40, Float_t bgmax=70, Byte_t polynom=1); //*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 SetMinLD(Float_t ratio)  { fMinLD = ratio; }  // Minimum ratio between length/dist
+    void SetMaxLD(Float_t ratio)  { fMaxLD = 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 Paint(Option_t *opt="");
+    void Draw(Option_t *option="");
+
+    static Double_t Significance(Double_t s, Double_t b);
+    static Double_t SignificanceLiMa(Double_t s, Double_t b, Double_t alpha=1);
+
+    ClassDef(MHFalseSource, 1) //3D-histogram in alpha, x and y
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFindSignificance.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFindSignificance.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFindSignificance.cc	(revision 3781)
@@ -0,0 +1,2047 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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);
+
+    //gStyle->SetOptFit(1011);
+
+    gROOT->SetSelectedPad(NULL);    
+    gStyle->SetPadLeftMargin(0.1);
+
+    fCanvas->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();
+
+    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-8-4/MagicSoft/Mars/mhist/MHFindSignificance.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFindSignificance.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFindSignificance.h	(revision 3781)
@@ -0,0 +1,193 @@
+#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);
+
+    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 GetSigLiMa()    const { return fSigLiMa; }
+    Float_t GetMbins()      const { return fMbins;   }
+    Float_t GetAlphasi()    const { return fAlphasi; }
+
+    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-8-4/MagicSoft/Mars/mhist/MHFlux.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFlux.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFlux.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHFlux.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFlux.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHFlux.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHGamma.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHGamma.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHGamma.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHGamma.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHGamma.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHGamma.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHHadronness.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHHadronness.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHHadronness.cc	(revision 3781)
@@ -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: Acceprtance 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);
+    fPhness = new TH1D("Phness", "Acceptance vs. Hadronness (Hadrons)", nbins, 0, 1);
+    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-8-4/MagicSoft/Mars/mhist/MHHadronness.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHHadronness.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHHadronness.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHOnSubtraction.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaPixel.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.cc	(revision 3781)
@@ -0,0 +1,351 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 (extension of Robert's MHSigmabarTheta)                    //
+//                                                                          //
+//  calculates - the 2D-histogram   sigmabar vs. Theta, and                 //
+//             - the 3D-histogram   sigma, pixel no., Theta                 //
+//             - the 3D-histogram   (sigma^2-sigmabar^2), pixel no., Theta  //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHSigmaTheta.h"
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+#include "MMcEvt.hxx"
+
+#include "MBinning.h"
+#include "MParList.h"
+#include "MSigmabar.h"
+
+#include "MGeomCam.h"
+
+#include "MPedPhotCam.h"
+#include "MPedPhotPix.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHSigmaTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHSigmaTheta::MHSigmaTheta(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MHSigmaTheta";
+    fTitle = title ? title : "2D histogram sigmabar vs. Theta";
+
+    fSigmaTheta.SetDirectory(NULL);
+    fSigmaTheta.SetName("2D-ThetaSigmabar");
+    fSigmaTheta.SetTitle("2D: \\bar{\\sigma}, \\Theta");
+    fSigmaTheta.SetXTitle("\\Theta [\\circ]");
+    fSigmaTheta.SetYTitle("Sigmabar");
+
+    fSigmaPixTheta.SetDirectory(NULL);
+    fSigmaPixTheta.SetName("3D-ThetaPixSigma");
+    fSigmaPixTheta.SetTitle("3D: \\Theta, Pixel Id, \\sigma");
+    fSigmaPixTheta.SetXTitle("\\Theta [\\circ]");
+    fSigmaPixTheta.SetYTitle("Pixel Id");
+    fSigmaPixTheta.SetZTitle("\\sigma");
+
+    fDiffPixTheta.SetDirectory(NULL);
+    fDiffPixTheta.SetName("3D-ThetaPixDiff");
+    fDiffPixTheta.SetTitle("3D: \\Theta, Pixel Id, {\\sigma}^{2}-\\bar{\\sigma}^{2}");
+    fDiffPixTheta.SetXTitle("\\Theta [\\circ]");
+    fDiffPixTheta.SetYTitle("Pixel Id");
+    fDiffPixTheta.SetZTitle("{\\sigma}^{2}-\\bar{\\sigma}^{2}");
+
+    // Set default binning
+    // FIXME: Maybe ist's necessary to adapt the value to the
+    // Magic default values
+    MBinning binsb;
+    MBinning binst;
+    MBinning binsd;
+    binsd.SetEdges(100, -10, 20);
+    binsb.SetEdges(100, 0, 10);
+    binst.SetEdgesCos(10, 0, 90);
+
+    MBinning binspix("BinningPixel");
+    binspix.SetEdges(578, -0.5, 577.5);
+
+    SetBinning(&fSigmaTheta,    &binst, &binsb);
+    SetBinning(&fSigmaPixTheta, &binst, &binspix, &binsb);
+    SetBinning(&fDiffPixTheta,  &binst, &binspix, &binsd);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+    }
+
+    fMcEvt = (MMcEvt*)plist->FindObject("MMcEvt");
+    if (!fMcEvt)
+        *fLog << warn << "MMcEvt not found... aborting." << endl;
+
+
+    fPed = (MPedPhotCam*)plist->FindObject("MPedPhotCam");
+    if (!fPed)
+    {
+        *fLog << err << "MPedPhotCam not found... aborting." << endl;
+        return kFALSE;
+    }
+    fPed->InitSize(fCam->GetNumPixels());
+
+
+    fEvt = (MCerPhotEvt*)plist->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fSigmabar = (MSigmabar*)plist->FindObject("MSigmabar");
+    if (!fSigmabar)
+    {
+        *fLog << err << "MSigmabar not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // Get Theta Binning
+    MBinning* binstheta  = (MBinning*)plist->FindObject("BinningTheta", "MBinning");
+    if (!binstheta)
+    {
+        *fLog << warn << "Object 'BinningTheta' [MBinning] not found... no binning applied." << endl;
+        return kTRUE;
+    }
+
+    // Get Sigmabar binning
+    MBinning* binssigma = (MBinning*)plist->FindObject("BinningSigmabar", "MBinning");
+    if (!binssigma)
+        *fLog << warn << "Object 'BinningSigmabar' [MBinning] not found... no binning applied." << endl;
+
+    // Get binning for (sigma^2-sigmabar^2)
+    MBinning* binsdiff  = (MBinning*)plist->FindObject("BinningDiffsigma2", "MBinning");
+    if (!binsdiff)
+        *fLog << warn << "Object 'BinningDiffsigma2' [MBinning] not found... no binning applied." << endl;
+
+    //FIXME: Missing: Apply new binning to only one axis!
+
+    // Get binning for pixel number
+    const UInt_t npix1 = fPed->GetSize()+1;
+    *fLog << "npix1 = " << npix1 << endl;
+    MBinning binspix("BinningPixel");
+    binspix.SetEdges(npix1, -0.5, npix1-0.5);
+
+    // Set binnings in histograms
+    if (binssigma)
+    {
+        SetBinning(&fSigmaTheta, binstheta, binssigma);
+        SetBinning(&fSigmaPixTheta, binstheta, &binspix, binssigma);
+    }
+
+    if (binsdiff)
+        SetBinning(&fDiffPixTheta,  binstheta, &binspix, binsdiff);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histograms
+//
+Bool_t MHSigmaTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    Double_t theta = fMcEvt ? fMcEvt->GetTelescopeTheta()*kRad2Deg : 0;
+    fSigmabar->Calc(*fCam, *fPed, *fEvt);
+    Double_t mysig = fSigmabar->GetSigmabarInner();
+
+    //*fLog << "theta, mysig = " << theta << ",  " << mysig << endl;
+
+    fSigmaTheta.Fill(theta, mysig);
+
+    const UInt_t npix = fEvt->GetNumPixels();
+
+    for (UInt_t i=0; i<npix; i++)
+    {
+        MCerPhotPix cerpix = (*fEvt)[i];
+        if (!cerpix.IsPixelUsed())
+            continue;
+
+        const Int_t id = cerpix.GetPixId();
+        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*sqrt(ratio));
+
+        const Double_t diff = sigma*sigma*ratio - mysig*mysig;
+        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, 2);
+
+    // 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->SetTitle("Distribution of \\Theta");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("No.of events");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    h = fDiffPixTheta.Project3D("zx");
+    h->SetDirectory(NULL);
+    h->SetTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2} vs. \\Theta (all pixels)");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2}");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    h = fSigmaPixTheta.Project3D("zx");
+    h->SetDirectory(NULL);
+    h->SetTitle("\\sigma_{ped} vs. \\Theta (all pixels)");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("\\sigma_{ped}");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    //pad->cd(7);
+    //gPad->SetBorderMode(0);
+    //h = fSigmaTheta.ProjectionY("ProjY-sigma", -1, 9999, "E");
+    //h->SetDirectory(NULL);
+    //h->SetTitle("Distribution of \\bar{\\sigma}_{ped}");
+    //h->SetXTitle("\\bar{\\sigma}_{ped}");
+    //h->SetYTitle("No.of events");
+    //h->Draw(opt);
+    //h->SetBit(kCanDelete);
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    h = fDiffPixTheta.Project3D("zy");
+    h->SetDirectory(NULL);
+    h->SetTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2} vs. pixel Id (all  \\Theta)");
+    h->SetXTitle("Pixel Id");
+    h->SetYTitle("\\sigma_{ped}^{2}-\\bar{\\sigma}_{ped}^{2}");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(6);
+    gPad->SetBorderMode(0);
+    h = fSigmaPixTheta.Project3D("zy");
+    h->SetDirectory(NULL);
+    h->SetTitle("\\sigma_{ped} vs. pixel Id (all  \\Theta)");
+    h->SetXTitle("Pixel Id");
+    h->SetYTitle("\\sigma_{ped}");
+    h->Draw("box");
+    h->SetBit(kCanDelete);
+
+    pad->cd(4);
+    fSigmaTheta.Draw(opt);
+
+    //pad->cd(8);
+    //fDiffPixTheta.Draw(opt);
+
+    //pad->cd(9);
+    //fSigmaPixTheta.Draw(opt);
+}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmaTheta.h	(revision 3781)
@@ -0,0 +1,65 @@
+#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 MGeomCam;
+class MCerPhotEvt;
+class MMcEvt;
+class MPedPhotCam;
+class MSigmabar;
+class MParList;
+
+
+class MHSigmaTheta : public MH
+{
+private:
+    const MGeomCam *fCam;        //!
+    MPedPhotCam    *fPed;        //!
+    MCerPhotEvt    *fEvt;        //!
+    MSigmabar      *fSigmabar;   //!
+    MMcEvt         *fMcEvt;      //!
+ 
+    TH2D fSigmaTheta;    // 2D-distribution sigmabar versus Theta; 
+                         // sigmabar is the average pedestasl sigma in an event
+    TH3D fSigmaPixTheta; // 3D-distr.:Theta, pixel, pedestal sigma
+    TH3D fDiffPixTheta;  // 3D-distr.:Theta, pixel, sigma^2-sigmabar^2
+
+    void Paint(Option_t *opt="");
+
+public:
+    MHSigmaTheta(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 *GetSigmaTheta() { return &fSigmaTheta; }
+    const TH2D *GetSigmaTheta() const { return &fSigmaTheta; }
+
+    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-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSigmabarTheta.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHStarMap.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHStarMap.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHStarMap.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHStarMap.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHStarMap.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHStarMap.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSupercuts.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSupercuts.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSupercuts.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHSupercuts.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSupercuts.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHSupercuts.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTheta.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHThetabarTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTime.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHThetabarTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHThetabarTime.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.cc	(revision 3781)
@@ -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    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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHTimeDiffTheta                                                         //
+//                                                                          //
+//  calculates the 2D-histogram   time-difference vs. Theta                 //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHTimeDiffTheta.h"
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+#include "MMcEvt.hxx"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHTimeDiffTheta);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram.
+//
+MHTimeDiffTheta::MHTimeDiffTheta(const char *name, const char *title)
+    : fLastTime(0), fHist()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHTimeDiffTheta";
+    fTitle = title ? title : "2-D histogram in Theta and time difference";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("\\Delta t [s]");
+    fHist.SetYTitle("\\Theta [\\circ]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHTimeDiffTheta::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* binsdtime = (MBinning*)plist->FindObject("BinningTimeDiff");
+   const MBinning* binstheta = (MBinning*)plist->FindObject("BinningTheta");
+   if (!binstheta || !binsdtime)
+   {
+       *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+       return kFALSE;      
+   }
+
+   SetBinning(&fHist, binsdtime, binstheta);
+
+   return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHTimeDiffTheta::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TH1 *h;
+
+    pad->Divide(2,2);
+
+    pad->cd(1);
+    gPad->SetLogy();
+    h = fHist.ProjectionX("ProjX_Theta", -1, 9999, "E");
+    h->SetTitle("Distribution of \\Delta t [s]");
+    h->SetXTitle("\\Delta t [s]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);;
+
+    pad->cd(2);
+    h = fHist.ProjectionY("ProjY_timediff", -1, 9999, "E");
+    h->SetTitle("Distribution of \\Theta [\\circ]");
+    h->SetXTitle("\\Theta [\\circ]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);;
+
+    pad->cd(3);
+    fHist.Draw(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histogram
+//
+Bool_t MHTimeDiffTheta::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t time = *fTime;
+
+    fHist.Fill(time-fLastTime, fMcEvt->GetTelescopeTheta()*kRad2Deg, w);
+    fLastTime = time;
+
+    return kTRUE;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTheta.h	(revision 3781)
@@ -0,0 +1,42 @@
+#ifndef MARS_MHTimeDiffTheta
+#define MARS_MHTimeDiffTheta
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MTime;
+class MMcEvt;
+
+class MParList;
+
+class MHTimeDiffTheta : public MH
+{
+private:
+    MTime  *fTime;   //!
+    MMcEvt *fMcEvt;  //!
+    Double_t fLastTime;
+
+    TH2D    fHist;
+
+public:
+    MHTimeDiffTheta(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(MHTimeDiffTheta, 0) //2D-histogram  time-diff vs. Theta
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.cc	(revision 3781)
@@ -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    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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHTimeDiffTime
+//
+//  calculates the 2D-histogram   time-difference vs. time
+//
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MHTimeDiffTime.h"
+
+#include <TCanvas.h>
+
+#include "MTime.h"
+
+#include "MBinning.h"
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHTimeDiffTime);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default Constructor. It sets name and title of the histogram
+//
+MHTimeDiffTime::MHTimeDiffTime(const char *name, const char *title)
+    : fLastTime(0), fHist()
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : "MHTimeDiffTime";
+    fTitle = title ? title : "2-D histogram in time and time difference";
+
+    fHist.SetDirectory(NULL);
+
+    fHist.SetXTitle("\\Delta t [s]");
+    fHist.SetYTitle("t [s]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the binnings and prepare the filling of the histogram
+//
+Bool_t MHTimeDiffTime::SetupFill(const MParList *plist)
+{
+    fTime = (MTime*)plist->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << dbginf << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MBinning* binsdtime = (MBinning*)plist->FindObject("BinningTimeDiff");
+    const MBinning* binstime  = (MBinning*)plist->FindObject("BinningTime");
+    if (!binstime || !binsdtime)
+    {
+        *fLog << err << dbginf << "At least one MBinning not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    SetBinning(&fHist, binsdtime, binstime);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram
+//
+void MHTimeDiffTime::Draw(Option_t *opt)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,2);
+
+    TH1D *h;
+
+    pad->cd(1);
+    gPad->SetLogy();
+    h = fHist.ProjectionX("ProjX_sumtime", -1, 9999, "E");
+    h->SetTitle("Distribution of \\Delta t [s]");
+    h->SetXTitle("\\Delta t [s]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(2);
+    h = fHist.ProjectionY("ProjY_sumtimediff", -1, 9999, "E");
+    h->SetTitle("Distribution of time [s]");
+    h->SetXTitle("time [s]");
+    h->SetYTitle("Counts");
+    h->Draw(opt);
+    h->SetBit(kCanDelete);
+
+    pad->cd(3);
+    fHist.DrawCopy(opt);
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Fill the histogram
+//
+Bool_t MHTimeDiffTime::Fill(const MParContainer *par, const Stat_t w)
+{
+    const Double_t time = *fTime;
+
+    fHist.Fill(time-fLastTime, time, w);
+    fLastTime = time;
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTimeDiffTime.h	(revision 3781)
@@ -0,0 +1,40 @@
+#ifndef MARS_MHTimeDiffTime
+#define MARS_MHTimeDiffTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+#ifndef ROOT_TH2
+#include <TH2.h>
+#endif
+
+class MTime;
+
+class MParList;
+
+class MHTimeDiffTime : public MH
+{
+private:
+    MTime *fTime;   //!
+    Double_t  fLastTime;
+
+    TH2D   fHist;
+
+public:
+    MHTimeDiffTime(const char *name=NULL, const char *title=NULL);
+
+    virtual Bool_t SetupFill(const MParList *pList);
+    virtual 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(MHTimeDiffTime, 0) //2D-histogram  time-diff vs. time
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTrigLvl0.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/MHTriggerLvl0.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhist/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhist/Makefile	(revision 3781)
@@ -0,0 +1,85 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Hist
+
+#
+# Library name to creatre
+#
+LIB   = mhist.a
+
+#
+#  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
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MHEvent.cc \
+           MHCamEvent.cc \
+           MHFadcPix.cc \
+           MHFadcCam.cc \
+           MHStarMap.cc \
+           MHEnergyTime.cc \
+           MHEnergyTheta.cc \
+           MHAlphaEnergyTime.cc \
+           MHAlphaEnergyTheta.cc \
+           MHBlindPixels.cc \
+           MHEffOnTime.cc \
+           MHTimeDiffTime.cc \
+           MHTimeDiffTheta.cc \
+           MHCompProb.cc \
+           MHHadronness.cc \
+           MHThetabarTime.cc \
+           MHThetabarTheta.cc \
+           MHGamma.cc \
+           MHFlux.cc \
+	   MHSigmaPixel.cc \
+	   MHSigmabarTheta.cc \
+	   MHSigmaTheta.cc \
+	   MHTriggerLvl0.cc \
+	   MHOnSubtraction.cc \
+	   MHFindSignificance.cc \
+	   MHCT1Supercuts.cc \
+           MHCamera.cc \
+           MHSupercuts.cc 
+#           MHCurrents.cc \
+
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcIncl.h	(revision 3781)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/HistMcLinkDef.h	(revision 3781)
@@ -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 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+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCT1CollectionArea.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.cc	(revision 3781)
@@ -0,0 +1,339 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//                                                                          //
+//  MHMcCollectionArea                                                      //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MHMcCollectionArea.h" 
+
+#include <TH2.h>
+#include <TCanvas.h>
+
+#include "MH.h"
+#include "MBinning.h"
+#include "MHMcEfficiency.h"
+#include "MHMcEnergyImpact.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHMcCollectionArea);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+//  Creates the three necessary histograms:
+//   - selected showers (input)
+//   - all showers (input)
+//   - collection area (result)
+//
+MHMcCollectionArea::MHMcCollectionArea(const char *name, const char *title)
+{ 
+    //   initialize the histogram for the distribution r vs E
+    //
+    //   we set the energy range from 2 Gev to 20000 GeV (in log 4 orders
+    //   of magnitude) and for each order we take 25 subdivision --> 100 xbins
+    //
+    //   we set the radius range from 0 m to 500 m with 10 m bin --> 50 ybins
+    //
+    fName  = name  ? name  : "MHMcCollectionArea";
+    fTitle = title ? title : "Collection Area vs. Energy";
+
+    MBinning binsx;
+    MBinning binsy;
+    binsx.SetEdgesLog(100, 2., 20000);
+    binsy.SetEdges   (50,  0,   500);
+
+    fHistAll = new TH2D;
+    fHistSel = new TH2D;
+    fHistCol = new TH1D;
+ 
+    MH::SetBinning(fHistAll, &binsx, &binsy);
+    MH::SetBinning(fHistSel, &binsx, &binsy);
+
+    fHistCol->SetName(fName);
+    fHistAll->SetName("AllEvents");
+    fHistSel->SetName("SelectedEvents");
+
+    fHistCol->SetTitle(fTitle);
+    fHistAll->SetTitle("All showers - Radius vs Energy distribution");
+    fHistSel->SetTitle("Selected showers - Radius vs Energy distribution");
+
+    fHistAll->SetDirectory(NULL);
+    fHistSel->SetDirectory(NULL);
+    fHistCol->SetDirectory(NULL);
+
+    fHistAll->UseCurrentStyle();
+    fHistSel->UseCurrentStyle();
+    fHistCol->UseCurrentStyle();
+
+    fHistAll->SetXTitle("E [GeV]");
+    fHistAll->SetYTitle("r [m]");
+    fHistAll->SetZTitle("N");
+
+    fHistSel->SetXTitle("E [GeV]");
+    fHistSel->SetYTitle("r [m]");
+    fHistSel->SetYTitle("N");
+
+    fHistCol->SetXTitle("E [GeV]");
+    fHistCol->SetYTitle("A [m^{2}]");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the three histograms
+//
+MHMcCollectionArea::~MHMcCollectionArea()
+{
+    delete fHistAll;
+    delete fHistSel;
+    delete fHistCol;
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains all showers
+//
+void MHMcCollectionArea::FillAll(Double_t energy, Double_t radius)
+{
+    fHistAll->Fill(energy, radius);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fill data into the histogram which contains the selected showers
+//
+void MHMcCollectionArea::FillSel(Double_t energy, Double_t radius)
+{
+    fHistSel->Fill(energy, radius);
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with all showers
+//
+void MHMcCollectionArea::DrawAll(Option_t* option)
+{
+    if (!gPad)
+        MH::MakeDefCanvas(fHistAll);
+
+    fHistAll->Draw(option);
+
+    gPad->SetLogx();
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw the histogram with the selected showers only.
+//
+void MHMcCollectionArea::DrawSel(Option_t* option)
+{
+    if (!gPad)
+        MH::MakeDefCanvas(fHistSel);
+
+    fHistSel->Draw(option);
+
+    gPad->SetLogx();
+
+    gPad->Modified();
+    gPad->Update();
+}
+
+void MHMcCollectionArea::Draw(Option_t* option)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    fHistCol->Draw(option);
+
+    pad->SetLogx();
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHMcCollectionArea::CalcEfficiency()
+{
+    Calc(*fHistSel, *fHistAll);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHMcCollectionArea::Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall)
+{
+    Calc((TH2D&)*mcsel.GetHist(), (TH2D&)*mcall.GetHist());
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHMcCollectionArea::Calc(TH2D &hsel, TH2D &hall)
+{
+    MH::SetBinning(fHistCol, hsel.GetXaxis());
+
+    fHistCol->Sumw2();
+
+    TH1D &psel = *hsel.ProjectionX();
+    TH1D &pall = *hall.ProjectionX();
+
+    TH1D &pally = *hall.ProjectionY();
+
+    Double_t max = 0.;
+    for (Int_t i = hall.GetNbinsY(); i > 0; i--)
+      if (pally.GetBinContent(i) > 0)
+	{
+	  max = pally.GetBinLowEdge(i+1);
+	  break;
+	}
+
+    fHistCol->Divide(&psel, &pall, TMath::Pi()*max*max, 1);
+    fHistCol->SetEntries(hsel.GetEntries());
+
+    delete &psel;
+    delete &pall;
+    delete &pally;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHMcCollectionArea::CalcEfficiency2()
+{
+    TH1D &histsel = *fHistSel->ProjectionX();
+    TH1D &histall = *fHistAll->ProjectionX();
+
+    TAxis &xaxis = *histsel.GetXaxis();
+    MH::SetBinning(fHistCol, &xaxis);
+    const Int_t nbinx = xaxis.GetNbins();
+
+    // -----------------------------------------------------------
+    //
+    // Impact parameter range:  TO BE FIXED! Impact parameter shoud be
+    // read from run header, but it is not yet in!!
+    //
+    const Float_t r1 = 0;
+    const Float_t r2 = 300;
+
+    *fLog << warn << endl << dbginf << "WARNING! I will assume a maximum impact parameter of 300 meters for the MC events. Check that this is the true one!" <<endl<<endl;
+    const Float_t total_area = TMath::Pi() * (r2*r2 - r1*r1);
+
+    for (Int_t ix=1; ix<=nbinx; ix++)
+    {
+        const Float_t Na = histall.GetBinContent(ix);
+
+        if (Na <= 0)
+            continue;
+
+        const Float_t Ns = histsel.GetBinContent(ix);
+
+        // 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;
+	
+	const Float_t col_area  =  eff * total_area;
+	const Float_t col_area_error =  efferr * total_area;
+
+        fHistCol->SetBinContent(ix, col_area);
+        fHistCol->SetBinError(ix, col_area_error);
+    }
+
+    delete &histsel;
+
+    SetReadyToSave();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculate the Efficiency (collection area) and set the 'ReadyToSave'
+//  flag
+//
+void MHMcCollectionArea::Calc(const MHMcEfficiency &heff)
+{
+    //
+    //  now calculate the Collection area for different
+    //  energies
+    //
+    TH2D &h = (TH2D&)*heff.GetHist();
+
+    MH::SetBinning(fHistCol, h.GetXaxis());
+
+    const Int_t nbinx = h.GetXaxis()->GetNbins();
+    const Int_t nbiny = h.GetYaxis()->GetNbins();
+
+    for (Int_t ix=1; ix<=nbinx; ix++)
+    {
+        Double_t errA = 0;
+        Double_t colA = 0;
+
+        for (Int_t iy=1; iy<=nbiny; iy++)
+        {
+            TAxis *yaxis = h.GetYaxis();
+
+            const Double_t r1  = yaxis->GetBinLowEdge(iy);
+            const Double_t r2  = yaxis->GetBinLowEdge(iy+1);
+
+            const Double_t A   = TMath::Pi() * (r2*r2 - r1*r1);
+
+            const Double_t eff = h.GetCellContent(ix, iy);
+            const Double_t efferr = h.GetCellError(ix, iy);
+
+            colA += eff*A;
+            errA += A*A * efferr*efferr;
+        }
+
+        fHistCol->SetBinContent(ix, colA);
+        fHistCol->SetBinError(ix, sqrt(errA));
+    }
+
+    SetReadyToSave();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcCollectionArea.h	(revision 3781)
@@ -0,0 +1,50 @@
+#ifndef MARS_MHMcCollectionArea
+#define MARS_MHMcCollectionArea
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1D;
+class TH2D;
+
+class MHMcEfficiency;
+class MHMcEnergyImpact;
+
+class MHMcCollectionArea : public MH
+{
+private:
+    TH2D *fHistAll; //! all simulated showers
+    TH2D *fHistSel; //! the selected showers
+
+    TH1D *fHistCol; //  the collection area
+
+    void Calc(TH2D &hsel, TH2D &hall);
+
+public:
+    MHMcCollectionArea(const char *name=NULL, const char *title=NULL);
+    ~MHMcCollectionArea();
+
+    void FillAll(Double_t energy, Double_t radius);
+    void FillSel(Double_t energy, Double_t radius);
+
+    void DrawAll(Option_t *option="");
+    void DrawSel(Option_t *option="");
+
+    const TH1D *GetHist()       { return fHistCol; }
+    const TH1D *GetHist() const { return fHistCol; }
+
+    TH2D *GetHistAll()    { return fHistAll; }
+
+    void Draw(Option_t *option="");
+
+    void CalcEfficiency();
+    void CalcEfficiency2();
+
+    void Calc(const MHMcEnergyImpact &mcsel, const MHMcEnergyImpact &mcall);
+    void Calc(const MHMcEfficiency &heff);
+
+    ClassDef(MHMcCollectionArea, 1)  // Data Container to calculate Collection Area
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcDifRate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiency.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyEnergy.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEfficiencyImpact.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergy.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyImpact.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcEnergyMigration.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcIntRate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcRate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcRate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcRate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcRate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcRate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcRate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/MHMcTriggerLvl2.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhistmc/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhistmc/Makefile	(revision 3781)
@@ -0,0 +1,66 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = HistMc
+
+#
+# Library name to creatre
+#
+LIB   = mhistmc.a
+
+#
+#  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
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+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
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
+
+
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeIncl.h	(revision 3781)
@@ -0,0 +1,6 @@
+#ifndef __CINT__
+
+#include <TF1.h>
+#include <TArrayI.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/HVsTimeLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.cc	(revision 3781)
@@ -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): Thomas Bretz, 12/2002 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHPixVsTime
+//
+// Display the pixel content versus time or event number
+//
+/////////////////////////////////////////////////////////////////////////////
+#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;
+
+// --------------------------------------------------------------------------
+//
+// 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  : "MHPixVsTime";
+    fTitle = title ? title : "Average of MPixVsTimes";
+
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+    }
+
+    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");
+    h->SetYTitle("");
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00");
+        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-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHPixVsTime.h	(revision 3781)
@@ -0,0 +1,59 @@
+#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:
+    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; }
+
+    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-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.cc	(revision 3781)
@@ -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): 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
+//
+/////////////////////////////////////////////////////////////////////////////
+#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;
+
+// --------------------------------------------------------------------------
+//
+// 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  : "MHSectorVsTime";
+    fTitle = title ? title : "Sector mean vs time";
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the fGraph
+//
+MHSectorVsTime::~MHSectorVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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("Camera");
+
+    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->GetN()==0)
+        return;
+        */
+
+    if (fGraph->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString str(opt);
+    /*
+    fGraph->GetHistogram()->SetXTitle("Time");
+    fGraph->GetHistogram()->GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00");
+    fGraph->GetHistogram()->GetXaxis()->SetTimeDisplay(1);
+    fGraph->GetHistogram()->GetXaxis()->SetLabelSize(0.033);
+
+    fGraph->GetHistogram()->SetYTitle("");
+     */
+    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");
+    h->SetYTitle("");
+
+    if (!fNameTime.IsNull())
+    {
+        TAxis *axe = h->GetXaxis();
+        axe->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00");
+        axe->SetTimeDisplay(1);
+        axe->SetLabelSize(0.025);
+    }
+
+    *fLog << dbg << "Draw: " << str << endl;
+    fGraph->Draw(str);
+/*
+    str.ReplaceAll("same", "");
+    str.ReplaceAll("A", "");
+
+    Int_t i=-1;
+    Int_t col=kRed;
+    while ((g=(TGraphErrors*)Next()))
+    {
+        i++;
+        *fLog << dbg << "Check" << i << ": " << str << endl;
+
+        while ((fMinSector>=0 && i<fMinSector) || (fMaxSector>=0 && i>fMaxSector))
+            i++;
+
+        h = g->GetHistogram();
+        g->SetLineColor(col++);
+
+        *fLog << dbg << "Draw" << i << ": " << g->GetTitle() << endl;
+        g->Draw(str);
+
+    }
+
+    pad->Modified();
+    pad->Update();*/
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHSectorVsTime.h	(revision 3781)
@@ -0,0 +1,70 @@
+#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:
+    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 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-8-4/MagicSoft/Mars/mhvstime/MHVsTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHVsTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHVsTime.cc	(revision 3781)
@@ -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, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MHVsTime
+//
+// Preliminary: the docu may be wrong!
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHVsTime.h"
+
+#include <ctype.h>   // tolower
+#include <fstream>
+
+#include <TPad.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+
+#include <TGraph.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MTime.h"
+#include "MParList.h"
+#include "MDataChain.h"
+#include "MRawEvtHeader.h"
+
+ClassImp(MHVsTime);
+
+using namespace std;
+
+static const TString gsDefName  = "MHVsTime";
+static const TString gsDefTitle = "Container for a graph vs time/evtnumber";
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHVsTime::MHVsTime(const char *rule)
+    : fGraph(NULL), fData(NULL), fScale(1), fUseEventNumber(0)
+{  
+    fName  = gsDefName;
+    fTitle = gsDefTitle;
+
+    if (!rule)
+        return;
+
+    fGraph = new TGraph;
+    fData = new MDataChain(rule);
+}
+
+// --------------------------------------------------------------------------
+//
+// Deletes the histogram
+//
+MHVsTime::~MHVsTime()
+{
+    if (fGraph)
+        delete fGraph;
+
+    if (fData)
+        delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// Return the data members used by the data chain to be used in
+// MTask::AddBranchToList
+//
+TString MHVsTime::GetDataMember() const
+{
+    return fData ? fData->GetDataMember() : (TString)"";
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MHVsTime::SetupFill(const MParList *plist)
+{
+    // reset histogram (necessary if the same eventloop is run more than once) 
+    //fGraph->Reset();
+
+    if (fData && !fData->PreProcess(plist))
+        return kFALSE;
+
+    if (fGraph)
+    {
+        delete fGraph;
+        fGraph = new TGraph;
+    }
+
+    TString title(fData ? GetRule() : (TString)"Histogram");
+    title += " vs ";
+    title += fUseEventNumber ? "Event Number" : "Time";
+
+    fGraph->SetNameTitle(fName, title);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the name of the histogram ant the MHVsTime container
+//
+void MHVsTime::SetName(const char *name)
+{
+    fGraph->SetName(name);
+    MParContainer::SetName(name);
+}
+
+// --------------------------------------------------------------------------
+//
+// Set the title of the histogram ant the MHVsTime container
+//
+void MHVsTime::SetTitle(const char *title)
+{
+    fGraph->SetTitle(title);
+    MParContainer::SetTitle(title);
+}
+
+// --------------------------------------------------------------------------
+//
+// Fills the one, two or three data members into our histogram
+//
+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;
+        }
+        t = tm->GetAxisTime();
+    }
+
+    const Double_t v = fData->GetValue()*fScale;
+
+    fGraph->SetPoint(fGraph->GetN(), t, v);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+//
+// 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 MHVsTime::Draw(Option_t *opt)
+{
+    if (fGraph->GetN()==0)
+        return;
+
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(fGraph);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    TString str(opt);
+
+    if (fUseEventNumber)
+        fGraph->GetHistogram()->SetXTitle("Event Number");
+    else
+    {
+        fGraph->GetHistogram()->SetXTitle("Time");
+        fGraph->GetHistogram()->GetXaxis()->SetTimeFormat("%H:%M:%S %F1995-01-01 00:00:00");
+        fGraph->GetHistogram()->GetXaxis()->SetTimeDisplay(1);
+        fGraph->GetHistogram()->GetXaxis()->SetLabelSize(0.033);
+    }
+    fGraph->GetHistogram()->SetYTitle(GetRule());
+
+    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);
+    if (fGraph->TestBit(kIsLogy))
+        pad->SetLogy();
+
+    pad->Modified();
+    pad->Update();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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();
+    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-8-4/MagicSoft/Mars/mhvstime/MHVsTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHVsTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/MHVsTime.h	(revision 3781)
@@ -0,0 +1,60 @@
+#ifndef MARS_MHVsTime
+#define MARS_MHVsTime
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TGraph;
+class MDataChain;
+
+class MHVsTime : public MH
+{
+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
+    Double_t    fScale; // Scale for axis (eg unit)
+
+    enum {
+        kIsLogy = BIT(18),
+        kUseEventNumber = BIT(20)
+    };
+
+    Bool_t fUseEventNumber;
+
+public:
+    MHVsTime(const char *rule=NULL);
+    ~MHVsTime();
+
+    void SetScale(Double_t scale) { fScale = scale; }
+
+    Int_t GetNbins() 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;
+
+    /*
+//    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 Draw(Option_t *opt=NULL);
+
+    MParContainer *New() const;
+
+    ClassDef(MHVsTime, 1) // Generalized 1/2/3D-histogram for Mars variables
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mhvstime/Makefile	(revision 3781)
@@ -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  = HVsTime
+
+#
+# Library name to creatre
+#
+LIB   = mhvstime.a
+
+#
+#  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
+# mhist (MHCamera)
+# mgui  (MCamEvent)
+# mraw  (MRawEvtHeader)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MHVsTime.cc \
+           MHPixVsTime.cc \
+           MHSectorVsTime.cc
+           
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageIncl.h	(revision 3781)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <TVector2.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/ImageLinkDef.h	(revision 3781)
@@ -0,0 +1,27 @@
+#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 MImgCleanTGB+;
+#pragma link C++ class MCameraSmooth+;
+
+#pragma link C++ class MHillas+;
+#pragma link C++ class MHillasSrc+;
+#pragma link C++ class MHillasSrcCalc+;
+#pragma link C++ class MHillasExt+;
+#pragma link C++ class MHillasCalc+;
+
+#pragma link C++ class MNewImagePar+;
+#pragma link C++ class MConcentration+;
+
+#pragma link C++ class MHHillas+;
+#pragma link C++ class MHHillasSrc+;
+#pragma link C++ class MHHillasExt+;
+#pragma link C++ class MHNewImagePar+;
+#pragma link C++ class MStereoPar+;
+#pragma link C++ class MStereoCalc+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MCameraSmooth.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MCameraSmooth.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MCameraSmooth.cc	(revision 3781)
@@ -0,0 +1,145 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+#include "MBlindPixels.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 MCerPhotEvt from the parlist (abort if missing)
+//  - get MGeomCam from the parameter list
+//
+Int_t MCameraSmooth::PreProcess (MParList *pList)
+{
+    fEvt = (MCerPhotEvt*)pList->FindObject("MCerPhotEvt");
+    if (!fEvt)
+    {
+        *fLog << err << dbginf << "MCerPhotEvt 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++)
+        {
+            MCerPhotPix &pix = (*fEvt)[i];
+
+            const Int_t id = pix.GetPixId();
+
+            const MGeomPix &gpix = (*fGeomCam)[id];
+
+            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 MCerPhotPix *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-8-4/MagicSoft/Mars/mimage/MCameraSmooth.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MCameraSmooth.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MCameraSmooth.h	(revision 3781)
@@ -0,0 +1,37 @@
+#ifndef MARS_MCameraSmooth
+#define MARS_MCameraSmooth
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MGeomCam;
+class MCerPhotEvt;
+class MBlindPixels;
+
+class MCameraSmooth : public MTask
+{
+private:
+    MCerPhotEvt *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-8-4/MagicSoft/Mars/mimage/MConcentration.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MConcentration.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MConcentration.cc	(revision 3781)
@@ -0,0 +1,163 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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>
+!   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 "MCerPhotPix.h"
+#include "MCerPhotEvt.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();
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. 
+//
+MConcentration::~MConcentration()
+{
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MCerPhotEvt &evt, const MHillas &hillas)
+{
+    Float_t maxpix[9] = {0,0,0,0,0,0,0,0,0};             // [#phot]
+
+    TIter Next(evt);
+    MCerPhotPix *pix = 0;
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+        const Int_t    pixid = pix->GetPixId();
+        const Double_t nphot = pix->GetNumPhotons()* geom.GetPixRatio(pixid);
+
+	// 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-8-4/MagicSoft/Mars/mimage/MConcentration.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MConcentration.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MConcentration.h	(revision 3781)
@@ -0,0 +1,40 @@
+#ifndef MARS_MConcentration
+#define MARS_MConcentration
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MCerPhotEvt;
+
+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);
+    ~MConcentration();
+
+    void Reset();
+
+    Int_t Calc(const MGeomCam &geom, const MCerPhotEvt &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-8-4/MagicSoft/Mars/mimage/MHHillas.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillas.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillas.cc	(revision 3781)
@@ -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  2001 <mailto:tbretz@uni-sw.gwdg.de>
+!              Wolfgang Wittek  2002 <mailto:wittek@mppmu.mpg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2002
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// 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"
+
+
+ClassImp(MHHillas);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Setup four histograms for Width, Length
+//
+MHHillas::MHHillas(const char *name, const char *title)
+    : 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)
+{
+    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, "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 = geom ? geom->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 *)
+{
+    TVirtualPad *pad = gPad ? gPad : MakeDefCanvas(this);
+    pad->SetBorderMode(0);
+
+    AppendPad("");
+
+    pad->Divide(2,3);
+
+    pad->cd(1);
+    gPad->SetBorderMode(0);
+    MH::DrawSame(*fWidth, *fLength, "Width'n'Length");
+
+    pad->cd(2);
+    gPad->SetBorderMode(0);
+    fDistC->Draw();
+
+    pad->cd(3);
+    gPad->SetBorderMode(0);
+    gPad->SetLogx();
+    fSize->Draw();
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    gPad->SetPad(0.51, 0.01, 0.99, 0.65);
+    SetColors();
+    fCenter->Draw("colz");
+
+    pad->cd(5);
+    gPad->SetBorderMode(0);
+    fDelta->Draw();
+
+    pad->cd(6);
+    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-8-4/MagicSoft/Mars/mimage/MHHillas.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillas.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillas.h	(revision 3781)
@@ -0,0 +1,60 @@
+#ifndef MARS_MHHillas
+#define MARS_MHHillas
+
+#ifndef MARS_MH
+#include "MH.h"
+#endif
+
+class TH1F;
+class TH2F;
+class MHillas;
+
+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;
+
+    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-8-4/MagicSoft/Mars/mimage/MHHillasExt.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasExt.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasExt.cc	(revision 3781)
@@ -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 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(101, 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);
+
+    pad->Modified();
+    pad->Update();
+}
+
+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-8-4/MagicSoft/Mars/mimage/MHHillasExt.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasExt.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasExt.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MHHillasSrc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasSrc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasSrc.cc	(revision 3781)
@@ -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  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",            181, -90,  90);
+    fDist  = new TH1F("Dist",  "Dist of Ellipse",             100,   0, 445);
+    fCosDA = new TH1F("CosDA", "cos(Delta,Alpha) of Ellipse", 101,  -1,   1);
+
+    fAlpha->SetDirectory(NULL);
+    fDist->SetDirectory(NULL);
+    fCosDA->SetDirectory(NULL);
+
+    fAlpha->SetXTitle("\\alpha [\\circ]");
+    fDist->SetXTitle("Dist [mm]");
+    fCosDA->SetXTitle("cos(\\delta,\\alpha)");
+
+    fAlpha->SetYTitle("Counts");
+    fDist->SetYTitle("Counts");
+    fCosDA->SetYTitle("Counts");
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the four histograms
+//
+MHHillasSrc::~MHHillasSrc()
+{
+    delete fAlpha;
+    delete fDist;
+    delete fCosDA;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    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);
+
+    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);
+
+    fDist->SetXTitle(mmscale ? "Dist [mm]" : "Dist [\\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();
+
+    delete pad->GetPad(3);
+
+    pad->cd(4);
+    gPad->SetBorderMode(0);
+    //gPad->SetLogy();
+    fCosDA->Draw();
+
+    pad->Modified();
+    pad->Update();
+}
+
+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-8-4/MagicSoft/Mars/mimage/MHHillasSrc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasSrc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHHillasSrc.h	(revision 3781)
@@ -0,0 +1,44 @@
+#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;     //->
+
+    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; }
+
+    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-8-4/MagicSoft/Mars/mimage/MHNewImagePar.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHNewImagePar.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHNewImagePar.cc	(revision 3781)
@@ -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): 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)
+{
+    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);
+    fHistConc.SetFillStyle(0);
+
+
+    MBinning bins;
+
+    bins.SetEdges(100, 0, 1);
+    bins.Apply(fHistLeakage1);
+    bins.Apply(fHistLeakage2);
+    bins.Apply(fHistConc);
+    bins.Apply(fHistConc1);
+
+    bins.SetEdges(75, 0, 150);
+    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)
+{
+    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 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()/1000000, w);
+    fHistCoreArea.Fill(h.GetCoreArea()/1000000, w);
+
+    fHistConc.Fill(h.GetConc(), w);
+    fHistConc1.Fill(h.GetConc1(), 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 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");
+
+    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");
+
+    pad->Modified();
+    pad->Update();
+}
+
+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-8-4/MagicSoft/Mars/mimage/MHNewImagePar.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHNewImagePar.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHNewImagePar.h	(revision 3781)
@@ -0,0 +1,55 @@
+#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
+
+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 Draw(Option_t *opt=NULL);
+
+    ClassDef(MHNewImagePar, 1) // Histograms of new image parameters
+};
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillas.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillas.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillas.cc	(revision 3781)
@@ -0,0 +1,342 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <fstream>
+
+#include <TArrayF.h>
+#include <TEllipse.h>
+#include <TVector2.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 << "Basic Image Parameters (" << GetName() << ")" << 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 << "Basic Image Parameters (" << GetName() << ")" << 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)
+{
+    if (fLength<0 || fWidth<0)
+        return;
+
+    TEllipse e(fMeanX, fMeanY, fLength, fWidth, 0, 360, fDelta*kRad2Deg+180);
+    e.SetLineWidth(2);
+    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 < 3
+//   2  size==0
+//   3  number of used pixel < 3
+//   4  CorrXY == 0
+//
+Int_t MHillas::Calc(const MGeomCam &geom, const MCerPhotEvt &evt)
+{
+    //
+    // sanity check 1
+    //
+    if (evt.GetNumPixels()<3)
+        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;
+
+    MCerPhotPix *pix = 0;
+
+    TIter Next(evt);
+    UInt_t numused = 0;
+    while ((pix=(MCerPhotPix*)Next()))
+    {
+        const MGeomPix &gpix = geom[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=(MCerPhotPix*)Next()))
+    {
+        const MGeomPix &gpix = geom[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-8-4/MagicSoft/Mars/mimage/MHillas.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillas.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillas.h	(revision 3781)
@@ -0,0 +1,56 @@
+#ifndef MARS_MHillas
+#define MARS_MHillas
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+class TVector2;
+
+class MGeomCam;
+class MCerPhotEvt;
+
+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 MCerPhotEvt &pix);
+
+    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; }
+
+    TVector2 GetMean() 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-8-4/MagicSoft/Mars/mimage/MHillasCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasCalc.cc	(revision 3781)
@@ -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, 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
+//
+//  By default MHillas, MHillasExt and MNewImagePar are calculated
+//  with the information from MCerPhotEvt and MGeomCam.
+//
+//  To switch of the calculation you may use:
+//   - Disable(MHillasCalc::kCalcHillas)
+//   - Disable(MHillasCalc::kCalcHillasExt)
+//   - Disable(MHillasCalc::kCalcNewImagePar)
+//
+//  If the calculation of MHillas is switched off a container MHillas
+//  in the parameter list is nevertheless necessary for the calculation
+//  of MHillasExt and MNewImagePar.
+//
+//  The names of the containers to be used can be set with:
+//   - SetNameHillas("NewName")
+//   - SetNameHillasExt("NewName")
+//   - SetNameNewImgPar("NewName")
+//
+//  Input Containers:
+//   MCerPhotEvt
+//   MGeomCam
+//   [MHillas]
+//
+//  Output Containers:
+//   [MHillas]
+//   MHillasExt
+//   MNewImagePar
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MHillasCalc.h"
+
+#include "MParList.h"
+
+#include "MHillas.h"
+#include "MHillasExt.h"
+#include "MNewImagePar.h"
+#include "MConcentration.h"
+#include "MCerPhotEvt.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MHillasCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MHillasCalc::MHillasCalc(const char *name, const char *title)
+    : fHilName("MHillas"), fHilExtName("MHillasExt"),
+    fImgParName("MNewImagePar"), fConcName("MConcentration"),
+    fFlags(0xff), fErrors(5)
+{
+    fName  = name  ? name  : "MHillasCalc";
+    fTitle = title ? title : "Calculate Hillas and other image parameters";
+}
+
+// --------------------------------------------------------------------------
+//
+// Check for a MCerPhotEvt object from which the Hillas are calculated.
+// Try to find the Geometry conatiner. Depending on the flags
+// try to find (and maybe create) the containers MHillas, MHillasExt,
+// MNewImagePar, too.
+//
+Int_t MHillasCalc::PreProcess(MParList *pList)
+{
+    // necessary
+    fCerPhotEvt = (MCerPhotEvt*)pList->FindObject(AddSerialNumber("MCerPhotEvt"));
+    if (!fCerPhotEvt)
+    {
+        *fLog << err << "MCerPhotEvt not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    // necessary
+    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(fHilName));
+    else
+    {
+        fHillas = (MHillas*)pList->FindObject(AddSerialNumber(fHilName), "MHillas");
+        *fLog << err << fHilName << " [MHillas] not found... aborting." << endl;
+    }
+    if (!fHillas)
+        return kFALSE;
+
+    // if enabled
+    if (TestFlag(kCalcHillasExt))
+    {
+        fHillasExt = (MHillasExt*)pList->FindCreateObj("MHillasExt", AddSerialNumber(fHilExtName));
+        if (!fHillasExt)
+            return kFALSE;
+    }
+
+    // if enabled
+    if (TestFlag(kCalcNewImagePar))
+    {
+        fNewImgPar = (MNewImagePar*)pList->FindCreateObj("MNewImagePar", AddSerialNumber(fImgParName));
+        if (!fNewImgPar)
+            return kFALSE;
+    }
+
+     // if enabled
+    if (TestFlag(kCalcConc))
+    {
+        fConc = (MConcentration*)pList->FindCreateObj("MConcentration", fConcName);
+        if (!fConc)
+            return kFALSE;
+    }
+
+   memset(fErrors.GetArray(), 0, sizeof(Char_t)*fErrors.GetSize());
+
+    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))
+    {
+        Int_t rc = fHillas->Calc(*fGeomCam, *fCerPhotEvt);
+        if (rc<0 || rc>4)
+        {
+            *fLog << err << dbginf << "MHillas::Calc returned unknown error code!" << endl;
+            return kFALSE;
+        }
+        fErrors[rc]++;
+        if (rc>0)
+            return kCONTINUE;
+    }
+
+    if (TestFlag(kCalcHillasExt))
+        fHillasExt->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+    if (TestFlag(kCalcNewImagePar))
+        fNewImgPar->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+    if (TestFlag(kCalcConc))
+        fConc->Calc(*fGeomCam, *fCerPhotEvt, *fHillas);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+//  This is used to print the output in the PostProcess. Later (having
+//  millions of events) we may want to improve the output.
+//
+void MHillasCalc::PrintSkipped(int i, const char *str) const
+{
+    *fLog << " " << setw(7) << fErrors[i] << " (";
+    *fLog << setw(3) << (int)(100.*fErrors[i]/GetNumExecutions());
+    *fLog << "%) Evts skipped: " << str << endl;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+
+    *fLog << inf << endl;
+    *fLog << GetDescriptor() << " execution statistics:" << endl;
+    *fLog << dec << setfill(' ');
+    PrintSkipped(1, "Less than 3 pixels (before cleaning)");
+    PrintSkipped(2, "Calculated Size == 0 (after cleaning)");
+    PrintSkipped(3, "Number of used pixels < 3");
+    PrintSkipped(4, "CorrXY==0");
+    *fLog << " " << (int)fErrors[0] << " (" << (int)(100.*fErrors[0]/GetNumExecutions()) << "%) Evts survived Hillas calculation!" << endl;
+    *fLog << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasCalc.h	(revision 3781)
@@ -0,0 +1,75 @@
+#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 MCerPhotEvt;
+class MHillas;
+class MHillasExt;
+class MNewImagePar;
+class MConcentration;
+
+class MHillasCalc : public MTask
+{
+    const MGeomCam    *fGeomCam;    //! Camera Geometry used to calculate Hillas
+    const MCerPhotEvt *fCerPhotEvt; //! Cerenkov Photon Event used for calculation
+
+    MHillas      *fHillas;          //! output container to store result
+    MHillasExt   *fHillasExt;       //! output container to store result
+    MNewImagePar *fNewImgPar;       //! output container to store result
+    MConcentration *fConc;          //! output container to store result
+
+    TString      fHilName;          // name of the 'MHillas' container
+    TString      fHilExtName;       // name of the 'MHillasExt' container
+    TString      fImgParName;       // name of the 'MNewImagePar' container
+    TString      fConcName;         // name of the 'MConcentration' container
+
+    Int_t        fFlags;            // Flags defining the behaviour of MHillasCalc
+
+    TArrayL      fErrors;           //! Error counter. Do we have to change to Double?
+
+    void PrintSkipped(int i, const char *str) const;
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    enum CalcCont_t {
+        kCalcHillas      = BIT(0),
+        kCalcHillasExt   = BIT(1),
+        //kCalcHillasSrc   = BIT(2),
+        kCalcNewImagePar = BIT(3),
+        kCalcConc        = BIT(4)
+    };
+
+    MHillasCalc(const char *name=NULL, const char *title=NULL);
+
+    void SetNameHillas(const char *name)    { fHilName = name;    }
+    void SetNameHillasExt(const char *name) { fHilExtName = name; }
+    void SetNameNewImgPar(const char *name) { fImgParName = name; }
+    void SetNameConc(const char *name) { fConcName = 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(MHillasCalc, 0) // Task to calculate Hillas and other image parameters
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.cc	(revision 3781)
@@ -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): 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 <fstream>
+#include <TArrayF.h>
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.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;
+}
+
+// -------------------------------------------------------------------------
+//
+// Print contents of MHillasExt to *fLog.
+//
+void MHillasExt::Print(Option_t *) const
+{
+    *fLog << all;
+    *fLog << "Extended Image Parameters (" << GetName() << ")" << 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 << "Extended Image Parameters (" << GetName() << ")" << 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;
+}
+
+// -------------------------------------------------------------------------
+//
+// calculation of additional parameters based on the camera geometry
+// and the cerenkov photon event
+//
+Int_t MHillasExt::Calc(const MGeomCam &geom, const MCerPhotEvt &evt, const MHillas &hil)
+{
+    //
+    //   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;
+
+    const UInt_t npixevt = evt.GetNumPixels();
+
+    Int_t maxpixid  = 0;
+    Float_t maxpix  = 0;
+    Float_t maxdist = 0;
+
+    for (UInt_t i=0; i<npixevt; i++)
+    {
+        const MCerPhotPix &pix = evt[i];
+        if (!pix.IsPixelUsed())
+            continue;
+
+        const Int_t pixid = pix.GetPixId();
+
+        const MGeomPix &gpix = geom[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(pixid);
+
+        if (nphot>maxpix)
+        {
+            maxpix   = nphot;                                  // [1]
+            maxpixid = 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);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasExt.h	(revision 3781)
@@ -0,0 +1,44 @@
+#ifndef MARS_MHillasExt
+#define MARS_MHillasExt
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class TArrayF;
+
+class MHillas;
+class MGeomCam;
+class MCerPhotEvt;
+
+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 MCerPhotEvt &pix, const MHillas &hil);
+
+    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-8-4/MagicSoft/Mars/mimage/MHillasSrc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrc.cc	(revision 3781)
@@ -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@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
+//
+/////////////////////////////////////////////////////////////////////////////
+#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;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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]
+
+    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 = 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]
+    const Double_t arg2 = cd*sx+sd*sy;          // [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]
+
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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() != 3)
+        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
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrc.h	(revision 3781)
@@ -0,0 +1,41 @@
+#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
+
+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; }
+
+    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, 4) // Container to hold source position dependant parameters
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.cc	(revision 3781)
@@ -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): 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
+//
+// FIXME: Merge with MHillasCalc
+//
+//  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))
+    {
+        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: Dist==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->SavePrimitive(out);
+
+    if (fSrcPos)
+        fSrcPos->SavePrimitive(out);
+
+    if (fHillasSrc)
+        fHillasSrc->SavePrimitive(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-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MHillasSrcCalc.h	(revision 3781)
@@ -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:
+    MHillas    *fHillas;     //! Pointer to the source independant hillas parameters
+    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-8-4/MagicSoft/Mars/mimage/MImgCleanStd.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanStd.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanStd.cc	(revision 3781)
@@ -0,0 +1,733 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 MCerPhotEvt are set as USED and NOT CORE. All the pixels belong
+// to RING number 1 (like USED pixels).
+// Look at MCerPhotPix.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 MCerPhotPix.
+// 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
+// (fInnerNoise = fSgb->GetSigmabarInner()) 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.
+// To calculate the average pedestal RMS of the inner pixels, you have to
+// add to the main task list an object of type MSigmabarCalc before the
+// MImgCleanStd object. To know how the calculation of fInnerNoise is done
+// look at the MSigmabarCalc Class.
+//
+// Example:
+//
+// MSigmabarCalc   sbcalc;
+// //creates an object that calcutates the average pedestal RMS
+// MImgCleanStd clean;
+// ...
+// tlist.AddToList(&sbcalc);
+// tlist.AddToList(&clean);
+//
+// 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
+//   MCerPhotEvt
+//   [MSigmabar]
+//
+//  Output Containers:
+//   MCerPhotEvt
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MImgCleanStd.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include <TGFrame.h>      // TGFrame
+#include <TGLabel.h>      // TGLabel
+#include <TGTextEntry.h>  // TGTextEntry
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MParList.h"
+#include "MSigmabar.h"
+#include "MCameraData.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.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";
+
+// --------------------------------------------------------------------------
+//
+// 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)
+    : fSgb(NULL), fCleaningMethod(kStandard), fCleanLvl1(lvl1),
+    fCleanLvl2(lvl2), fCleanRings(1)
+
+{
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+
+    Print();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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
+    //
+    MCerPhotPix *pix;
+
+    // Loop over all pixels
+    MCerPhotEvtIter Next(fEvt, kFALSE);
+    while ((pix=static_cast<MCerPhotPix*>(Next())))
+        if (!pix->IsPixelUnmapped() && data[pix->GetPixId()] <= fCleanLvl1)
+            pix->SetPixelUnused();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Check if the survived pixel have a neighbor, that also
+//  survived, otherwise set pixel to unused (removes pixels without
+//  neighbors).
+//
+void MImgCleanStd::CleanStep2()
+{
+    MCerPhotPix *pix;
+
+    // Loop over used pixels only
+    TIter Next(*fEvt);
+
+    while ((pix=static_cast<MCerPhotPix*>(Next())))
+          {
+        // get pixel id of this entry
+        const Int_t idx = pix->GetPixId();
+ 
+        // 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)
+            pix->SetPixelUnused();
+    }
+
+    //
+    // now we declare all pixels that survive as CorePixels
+    //
+
+    Next.Reset();
+    while ((pix=static_cast<MCerPhotPix*>(Next())))
+      {
+	if ( pix->IsPixelUsed())
+        pix->SetPixelCore();}
+} 
+
+void MImgCleanStd::CleanStep3b(MCerPhotPix &pix)
+{
+    const Int_t idx = 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)[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, MCerPhotPix &pix)
+{
+    //
+    // 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.
+    //
+    const Int_t idx = pix.GetPixId();
+
+    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);
+
+        MCerPhotPix *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++)
+    {
+        MCerPhotPix *pix;
+
+        // Loop over all pixels
+
+        MCerPhotEvtIter NextAll(fEvt, kFALSE);
+        while ((pix=static_cast<MCerPhotPix*>(NextAll())))
+	  {
+            //
+	    // if pixel is a core pixel or unmapped, go to the next pixel
+            //
+	  if (pix->IsPixelCore())
+	    {
+	    continue;}
+	  if (pix->IsPixelUnmapped())
+	    {
+	    continue;}
+	  
+	  if (data[pix->GetPixId()] <= fCleanLvl2)
+	    {
+	      continue;}
+
+	  if (r==1)
+	    {
+	    CleanStep3b(*pix);}
+	  else
+	    {
+	    CleanStep4(r, *pix);}
+	  
+        }
+    }
+}
+
+// --------------------------------------------------------------------------
+//
+//  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("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;
+    }
+
+    if (fCleaningMethod == kDemocratic)
+    {
+        fSgb = (MSigmabar*)pList->FindObject(AddSerialNumber("MSigmabar"));
+        if (!fSgb)
+        {
+            *fLog << dbginf << "MSigmabar not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+    else
+    {
+        fPed = (MPedPhotCam*)pList->FindObject(AddSerialNumber("MPedPhotCam"));
+        if (!fPed)
+        {
+            *fLog << dbginf << "MPedPhotCam not found... aborting." << endl;
+            return kFALSE;
+        }
+    }
+
+    fData = (MCameraData*)pList->FindCreateObj(AddSerialNumber("MCameraData"));
+    if (!fData)
+        return kFALSE;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Cleans the image.
+//
+Int_t MImgCleanStd::Process()
+{
+    if (fSgb)
+        fData->CalcCleaningLevel(*fEvt, *fSgb, *fCam);
+    else
+        fData->CalcCleaningLevel(*fEvt, *fPed, *fCam);
+
+#ifdef DEBUG
+    *fLog << all << "CleanStep 1" << endl;
+#endif
+    CleanStep1();
+
+#ifdef DEBUG
+    *fLog << all << "CleanStep 2" << endl;
+#endif
+    CleanStep2();
+#ifdef DEBUG
+    *fLog << all << "CleanStep 3" << endl;
+#endif
+    CleanStep3();
+#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;
+    }
+    *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 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 << " 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 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!=kDemocratic)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetMethod(MImgCleanStd::kDemocratic);" << endl;
+
+    if (fCleanRings==1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetCleanRings(" << fCleanRings << ");" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanStd.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanStd.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanStd.h	(revision 3781)
@@ -0,0 +1,71 @@
+#ifndef MARS_MImgCleanStd
+#define MARS_MImgCleanStd
+
+#ifndef MARS_MGTask
+#include "MGTask.h"
+#endif
+
+class MGeomCam;
+class MSigmabar;
+class MCerPhotPix;
+class MCerPhotEvt;
+class MPedPhotCam;
+class MCameraData;
+
+class MGGroupFrame;
+
+class MImgCleanStd : public MGTask
+{
+public:
+    typedef enum {
+        kStandard,
+        kDemocratic
+    } CleaningMethod_t;
+
+private:
+    const MGeomCam    *fCam;  //!
+          MCerPhotEvt *fEvt;  //!
+          MSigmabar   *fSgb;  //!
+          MPedPhotCam *fPed;  //!
+          MCameraData *fData; //!
+
+    CleaningMethod_t fCleaningMethod;
+
+    Float_t fCleanLvl1;
+    Float_t fCleanLvl2;
+
+    UShort_t fCleanRings;
+
+    Float_t fInnerNoise;      //!
+
+    void CreateGuiElements(MGGroupFrame *f);
+    void StreamPrimitive(ofstream &out) const;
+
+    void   CleanStep3b(MCerPhotPix &pix);
+    void   CleanStep4(UShort_t r, MCerPhotPix &pix);
+
+    void  CleanStep1();
+    void  CleanStep2();
+    void  CleanStep3();
+
+    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; }
+
+    Bool_t ProcessMessage(Int_t msg, Int_t submsg, Long_t param1, Long_t param2);
+
+    ClassDef(MImgCleanStd, 2)    // task doing the image cleaning
+}; 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MImgCleanTGB.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MNewImagePar.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImagePar.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImagePar.cc	(revision 3781)
@@ -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 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
+//
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MNewImagePar.h"
+
+#include <fstream>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MHillas.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MCerPhotEvt.h"
+#include "MCerPhotPix.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";
+}
+
+// --------------------------------------------------------------------------
+//
+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;
+
+    fNumSaturatedPixels = -1;
+    fNumHGSaturatedPixels = -1;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Calculation of new image parameters
+//
+void MNewImagePar::Calc(const MGeomCam &geom, const MCerPhotEvt &evt,
+                        const MHillas &hillas)
+{
+    fNumUsedPixels = 0;
+    fNumCorePixels = 0;
+
+    fUsedArea = 0;
+    fCoreArea = 0;
+
+    fNumSaturatedPixels = 0;
+    fNumHGSaturatedPixels = 0;
+
+    fInnerSize = 0;
+
+    const UInt_t npixevt = evt.GetNumPixels();
+
+    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]
+
+    for (UInt_t i=0; i<npixevt; i++)
+    {
+        const MCerPhotPix &pix = evt[i];
+
+        // count saturated pixels
+	if (pix.IsPixelHGSaturated())
+            fNumHGSaturatedPixels++;
+	if (pix.IsPixelSaturated())
+            fNumSaturatedPixels++;
+
+        // skip unused pixels
+        if (!pix.IsPixelUsed())
+            continue;
+
+        // Get geometry of pixel
+        const Int_t pixid = pix.GetPixId();
+        const MGeomPix &gpix = geom[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(pixid);
+
+	// count inner pixels: To dependent on MAGIC Camera --> FIXME
+
+        if (pixid<397){
+            fInnerSize += nphot;
+            if(pixid>270){
+                edgepixin2 += nphot;
+                if(pixid>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 << "New Image Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Leakage1       [1]   = " << fLeakage1             << endl;
+    *fLog << " - Leakage2       [1]   = " << fLeakage2             << 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;
+    *fLog << " - Sat.Pixels/HG  [#]   = " << fNumHGSaturatedPixels << " Pixels" << endl;
+    *fLog << " - Sat.Pixels/LG  [#]   = " << fNumSaturatedPixels   << " Pixels" << 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 << "New Image Parameters (" << GetName() << ")" << endl;
+    *fLog << " - Leakage1       [1]   = " << fLeakage1             << endl;
+    *fLog << " - Leakage2       [1]   = " << fLeakage2             << 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;
+    *fLog << " - Sat.Pixels/HG  [#]   = " << fNumHGSaturatedPixels << " Pixels" << endl;
+    *fLog << " - Sat.Pixels/LG  [#]   = " << fNumSaturatedPixels   << " Pixels" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImagePar.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImagePar.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImagePar.h	(revision 3781)
@@ -0,0 +1,60 @@
+#ifndef MARS_MNewImagePar
+#define MARS_MNewImagePar
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MHillas;
+class MGeomCam;
+class MCerPhotEvt;
+
+class MNewImagePar : public MParContainer
+{
+private:
+    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
+
+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 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; }
+
+    Short_t GetNumSaturatedPixels() const { return fNumSaturatedPixels; }
+    Short_t GetNumHGSaturatedPixels() const { return fNumHGSaturatedPixels; }
+
+    void Print(Option_t *opt=NULL) const;
+    void Print(const MGeomCam &geom) const;
+
+    void Calc(const MGeomCam &geom, const MCerPhotEvt &evt,
+              const MHillas &hillas);
+
+    ClassDef(MNewImagePar, 3) // Container to hold new image parameters
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MNewImageParCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MStereoCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MStereoCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MStereoPar.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoPar.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoPar.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/MStereoPar.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoPar.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/MStereoPar.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mimage/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mimage/Makefile	(revision 3781)
@@ -0,0 +1,62 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Image
+
+#
+# Library name to creatre
+#
+LIB   = mimage.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mhbase -I../mgeom -I../manalysis -I../mgui -I../mmc \
+	   -I../mpointing
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MImgCleanStd.cc \
+	   MImgCleanTGB.cc \
+           MCameraSmooth.cc \
+           MHillas.cc \
+           MHillasSrc.cc \
+           MHillasExt.cc \
+           MHillasCalc.cc \
+           MHillasSrcCalc.cc \
+	   MNewImagePar.cc \
+	   MConcentration.cc \
+           MHHillas.cc \
+           MHHillasSrc.cc \
+           MHHillasExt.cc \
+	   MHNewImagePar.cc \
+	   MStereoPar.cc \
+	   MStereoCalc.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/JobsLinkDef.h	(revision 3781)
@@ -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 MJPedestal+;
+#pragma link C++ class MJCalibration+;
+#pragma link C++ class MJExtractSignal+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.cc	(revision 3781)
@@ -0,0 +1,1172 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+/////////////////////////////////////////////////////////////////////////////
+//
+//  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 chosen via the command SetExtractorLevel(UInt_t i)
+// Up to now, the following extractors are available:
+// i=1: Use MExtractSignal  (fixed window)
+// i=2: Use MExtractSignal2 (sliding window: default)
+// i=3: Use MExtractSignal3 (coherent sliding window for all pixels)
+//
+// 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 SetDataCheck() is set, only the most important ones are displayed 
+// Otherwise, (default: SetNormalDisplay()), a good selection of plots is given
+//
+// See also: MHCalibrationChargePix, MHCalibrationChargeCam, MHGausEvents
+//           MHCalibrationChargeBlindPix, MHCalibrationChargePINDiode
+//           MCalibrationChargePix, MCalibrationChargeCam, MCalibrationChargeCalc
+//           MCalibrationChargeBlindPix, 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 chosen via the command SetArrivalTimeLevel(UInt_t i)
+// Up to now, the following extractors are available:
+// i=1: Use MArrivalTimeCalc  (using MCubicSpline, arrival time == position at half maximum)
+// i=2: Use MArrivalTimeCalc2 (mean time of fWindowSize time slices with the highest integral content: default)
+//
+// See also: MHCalibrationRelTimePix, MHCalibrationRelTimeCam, MHGausEvents
+//           MCalibrationRelTimePix, MCalibrationRelTimeCam
+//           MBadPixelsPix, MBadPixelsCam
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJCalibration.h"
+
+#include <TF1.h>
+#include <TFile.h>
+#include <TStyle.h>
+#include <TCanvas.h>
+#include <TSystem.h>
+#include <TProfile.h>
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRunIter.h"
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+
+#include "MHCamera.h"
+#include "MGeomCam.h"
+
+#include "MPedestalCam.h"
+#include "MCalibrationCam.h"
+#include "MCalibrationQECam.h"
+#include "MCalibrationChargeCam.h"
+#include "MCalibrationChargePINDiode.h"
+#include "MCalibrationChargeBlindPix.h"
+#include "MCalibrationChargeCalc.h"
+
+#include "MHGausEvents.h"
+#include "MHCalibrationCam.h"
+#include "MHCalibrationChargeCam.h"
+#include "MHCalibrationRelTimeCam.h"
+#include "MCalibrationRelTimeCam.h"
+
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MBadPixelsCam.h"
+#include "MExtractSignal.h"
+#include "MExtractPINDiode.h"
+#include "MExtractBlindPixel.h"
+#include "MExtractSignal2.h"
+#include "MExtractSignal3.h"
+#include "MFCosmics.h"
+#include "MContinue.h"
+#include "MFillH.h"
+
+#include "MArrivalTimeCam.h"
+#include "MArrivalTimeCalc.h"
+#include "MArrivalTimeCalc2.h"
+
+#include "MJCalibration.h"
+#include "MStatusDisplay.h"
+
+ClassImp(MJCalibration);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+// Sets fRuns to 0, fColor to kNONE, fDisplay to kNormalDisplay, 
+// fRelTime to kFALSE, fExtractorLevel to 2, fArrivalTimeLevel to 2
+//
+MJCalibration::MJCalibration(const char *name, const char *title) 
+    : fRuns(0), fColor(MCalibrationCam::kNONE), fDisplayType(kNormalDisplay),
+      fRelTimes(kFALSE), fExtractorLevel(2), fArrivalTimeLevel(2)
+{
+  fName  = name  ? name  : "MJCalibration";
+  fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MJCalibration::CamDraw(TCanvas &c, const Int_t x, const Int_t y, const MHCamera &cam1, 
+                            const Int_t fit, const Int_t rad)
+{
+    c.cd(x);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+    MHCamera *obj1=(MHCamera*)cam1.DrawCopy("hist");
+    obj1->SetDirectory(NULL);
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->SetPrettyPalette();
+    obj1->AddNotify(&fCalibrationCam);
+    obj1->Draw();
+
+    if (rad)
+      {
+        c.cd(x+2*y);
+        gPad->SetBorderMode(0);
+        gPad->SetTicks();
+        DrawRadialProfile(obj1);
+      }
+    
+
+    if (!fit)
+        return;
+
+    c.cd(rad ? x+3*y : x+2*y);
+    gPad->SetBorderMode(0);
+    gPad->SetTicks();
+    DrawProjection(obj1, fit);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 SetDataCheck() 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;
+
+    //
+    // Update display
+    //
+    TString title = fDisplay->GetTitle();
+    title += "--  Calibration ";
+    title += fRuns->GetRunsAsString();
+    title += "  --";
+    fDisplay->SetTitle(title);
+
+    //
+    // Get container from list
+    //
+    MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+
+    // Create histograms to display
+    MHCamera disp1 (geomcam, "Cal;Charge",            "Fitted Mean Charges");
+    MHCamera disp2 (geomcam, "Cal;SigmaCharge",       "Sigma of Fitted Charges");
+    MHCamera disp3 (geomcam, "Cal;RSigma",            "Reduced Sigmas");
+    MHCamera disp4 (geomcam, "Cal;RSigma/Charge",     "Reduced Sigma per Charge");
+    MHCamera disp5 (geomcam, "Cal;FFactorPhe",        "Nr. of Phe's (F-Factor Method)");
+    MHCamera disp6 (geomcam, "Cal;FFactorConv",       "Conversion Factor (F-Factor Method)");
+    MHCamera disp7 (geomcam, "Cal;FFactorFFactor",    "Total F-Factor (F-Factor Method)");
+    MHCamera disp8 (geomcam, "Cal;CascadesQEFFactor", "Cascades QE (F-Factor Method)");
+    MHCamera disp9 (geomcam, "Cal;CascadesQEBlindPix","Cascades QE (Blind Pixel Method)");
+    MHCamera disp10(geomcam, "Cal;CascadesQEPINDiode","Cascades QE (PIN Diode Method)");
+    MHCamera disp11(geomcam, "Cal;CascadesQECombined","Cascades QE (Combined Method)");
+    MHCamera disp12(geomcam, "Cal;FFactorValid",      "Pixels with valid F-Factor calibration");
+    MHCamera disp13(geomcam, "Cal;BlindPixelValid",   "Pixels with valid BlindPixel calibration");
+    MHCamera disp14(geomcam, "Cal;PINdiodeValid",     "Pixels with valid PINDiode calibration");
+    MHCamera disp15(geomcam, "Cal;CombinedValid",     "Pixels with valid Combined calibration");
+    MHCamera disp16(geomcam, "Cal;Saturation",        "Pixels with saturated Hi Gain");
+    MHCamera disp17(geomcam, "Cal;ConversionMeans",   "Conversion HiGain.vs.LoGain Means");
+    MHCamera disp18(geomcam, "Cal;ConversionSigmas",  "Conversion HiGain.vs.LoGain Sigmas");
+    MHCamera disp19(geomcam, "Cal;HiGainPickup",      "Number Pickup events Hi Gain");
+    MHCamera disp20(geomcam, "Cal;LoGainPickup",      "Number Pickup events Lo Gain");
+    MHCamera disp21(geomcam, "Cal;HiGainBlackout",    "Number Blackout events Hi Gain");
+    MHCamera disp22(geomcam, "Cal;LoGainBlackout",    "Number Blackout events Lo Gain");
+    MHCamera disp23(geomcam, "Cal;Excluded",          "Pixels previously excluded");
+    MHCamera disp24(geomcam, "Bad;UnSuitable",        "Pixels not suited for further analysis");
+    MHCamera disp25(geomcam, "Bad;UnReliable",        "Pixels not reliable for further analysis");
+    MHCamera disp26(geomcam, "Bad;HiGainOscillating", "Oscillating Pixels High Gain");
+    MHCamera disp27(geomcam, "Bad;LoGainOscillating", "Oscillating Pixels Low Gain");
+    MHCamera disp28(geomcam, "Cal;AbsTimeMean",       "Abs. Arrival Times");
+    MHCamera disp29(geomcam, "Cal;AbsTimeRms",        "RMS of Arrival Times");
+    MHCamera disp30(geomcam, "time;MeanTime",         "Mean Rel. Arrival Times");
+    MHCamera disp31(geomcam, "time;SigmaTime",        "Sigma Rel. Arrival Times");
+    MHCamera disp32(geomcam, "time;TimeProb",         "Probability of Time Fit");
+    MHCamera disp33(geomcam, "time;NotFitValid",      "Pixels with not valid fit results");
+    MHCamera disp34(geomcam, "time;Oscillating",      "Oscillating Pixels");
+
+
+    
+    // Fitted charge means and sigmas
+    disp1.SetCamContent(fCalibrationCam,  0);
+    disp1.SetCamError(  fCalibrationCam,  1);
+    disp2.SetCamContent(fCalibrationCam,  2);
+    disp2.SetCamError(  fCalibrationCam,  3);
+
+    // Reduced Sigmas and reduced sigmas per charge
+    disp3.SetCamContent(fCalibrationCam,  5);
+    disp3.SetCamError(  fCalibrationCam,  6);
+    disp4.SetCamContent(fCalibrationCam,  7);
+    disp4.SetCamError(  fCalibrationCam,  8);
+
+    // F-Factor Method
+    disp5.SetCamContent(fCalibrationCam,  9);
+    disp5.SetCamError(  fCalibrationCam, 10);
+    disp6.SetCamContent(fCalibrationCam, 11);
+    disp6.SetCamError(  fCalibrationCam, 12);
+    disp7.SetCamContent(fCalibrationCam, 13);
+    disp7.SetCamError(  fCalibrationCam, 14);
+
+    // Quantum Efficiencies
+    disp8.SetCamContent (fQECam, 0 );
+    disp8.SetCamError   (fQECam, 1 );
+    disp9.SetCamContent (fQECam, 2 );
+    disp9.SetCamError   (fQECam, 3 );
+    disp10.SetCamContent(fQECam, 4 );
+    disp10.SetCamError  (fQECam, 5 );
+    disp11.SetCamContent(fQECam, 6 );
+    disp11.SetCamError  (fQECam, 7 );
+
+    // Valid flags
+    disp12.SetCamContent(fQECam, 8 );
+    disp13.SetCamContent(fQECam, 9 );
+    disp14.SetCamContent(fQECam, 10);
+    disp15.SetCamContent(fQECam, 11);
+
+    // Conversion Hi-Lo
+    disp16.SetCamContent(fCalibrationCam, 25);
+    disp17.SetCamContent(fCalibrationCam, 16);
+    disp17.SetCamError  (fCalibrationCam, 17);
+    disp18.SetCamContent(fCalibrationCam, 18);
+    disp18.SetCamError  (fCalibrationCam, 19);
+
+    // Pickup and Blackout
+    disp19.SetCamContent(fCalibrationCam, 21);
+    disp20.SetCamContent(fCalibrationCam, 22);
+    disp21.SetCamContent(fCalibrationCam, 23);
+    disp22.SetCamContent(fCalibrationCam, 24);
+
+    // Pixels with defects
+    disp23.SetCamContent(fCalibrationCam, 20);
+    disp24.SetCamContent(fBadPixels, 1);
+    disp25.SetCamContent(fBadPixels, 3);
+
+    // Oscillations
+    disp26.SetCamContent(fBadPixels, 10);
+    disp27.SetCamContent(fBadPixels, 11);
+
+    // Arrival Times
+    disp28.SetCamContent(fCalibrationCam, 26);
+    disp28.SetCamError(  fCalibrationCam, 27);
+    disp29.SetCamContent(fCalibrationCam, 27);
+
+    disp1.SetYTitle("Q [FADC counts]");
+    disp2.SetYTitle("\\sigma_{Q} [FADC counts]");
+
+    disp3.SetYTitle("\\sqrt{\\sigma^{2}_{Q} - RMS^{2}_{Ped}} [FADC Counts]");
+    disp4.SetYTitle("Red.Sigma/<Q> [1]");
+
+    disp5.SetYTitle("Nr. Phe's [1]");
+    disp6.SetYTitle("Conv.Factor [PhE/FADC counts]");
+    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 slice]");
+    disp29.SetYTitle("RMS Abs. Time [FADC slices]");
+
+    if (fRelTimes)
+      {
+
+        disp30.SetCamContent(fRelTimeCam,0);
+        disp30.SetCamError(  fRelTimeCam,1);
+        disp31.SetCamContent(fRelTimeCam,2);
+        disp31.SetCamError(  fRelTimeCam,3);
+        disp32.SetCamContent(fRelTimeCam,4);
+        disp33.SetCamContent(fBadPixels,20);
+        disp34.SetCamContent(fBadPixels,21);
+    
+        disp30.SetYTitle("Time Offset [ns]");
+        disp31.SetYTitle("Timing resolution [ns]");
+        disp32.SetYTitle("P_{Time} [1]");
+        disp33.SetYTitle("[1]");
+        disp34.SetYTitle("[1]");
+      }
+    
+    gStyle->SetOptStat(1111);
+    gStyle->SetOptFit();
+
+    if (fDisplayType == kDataCheck)
+      {
+        TCanvas &c1 = fDisplay->AddTab("Fit.Charge");
+        c1.Divide(3, 3);
+        
+        CamDraw(c1, 1, 3, disp1, 2);
+        CamDraw(c1, 2, 3, disp4, 2);
+        CamDraw(c1, 3, 3, disp28, 2);
+
+        //  F-Factor
+        TCanvas &c2 = fDisplay->AddTab("Phe's");
+        c2.Divide(3,4);
+        
+        CamDraw(c2, 1, 3, disp6, 2, 1);
+        CamDraw(c2, 2, 3, disp7, 2, 1);
+        CamDraw(c2, 3, 3, disp8, 2, 1);
+
+        // QE's
+        TCanvas &c3 = fDisplay->AddTab("QE's");
+        c3.Divide(3,4);
+
+        CamDraw(c3, 1, 3, disp8,  2, 1);
+        CamDraw(c3, 2, 3, disp9,  2, 1);
+        CamDraw(c3, 3, 3, disp10, 2, 1);
+
+        // Defects
+        TCanvas &c4 = fDisplay->AddTab("Defect");
+        c4.Divide(3,2);
+        
+        CamDraw(c4, 1, 3, disp23, 0);
+        CamDraw(c4, 2, 3, disp24, 0);
+        CamDraw(c4, 3, 3, disp25, 0);
+
+        if (fRelTimes)
+          {
+            // Rel. Times
+            TCanvas &c5 = fDisplay->AddTab("Rel. Times");
+            c5.Divide(2,4);
+            
+            CamDraw(c5, 1, 2, disp30, 2);
+            CamDraw(c5, 2, 2, disp31, 2);
+          }
+
+
+        return;
+      }
+    
+    if (fDisplayType == kNormalDisplay)
+      {
+
+        // Charges
+        TCanvas &c11 = fDisplay->AddTab("Fit.Charge");
+        c11.Divide(2, 4);
+        
+        CamDraw(c11, 1, 2, disp1, 2, 1);
+        CamDraw(c11, 2, 2, disp2, 2, 1);
+        
+        // Reduced Sigmas
+        TCanvas &c12 = fDisplay->AddTab("Red.Sigma");
+        c12.Divide(2,4);
+        
+        CamDraw(c12, 1, 2, disp3, 2, 1);
+        CamDraw(c12, 2, 2, disp4, 2, 1);
+        
+        //  F-Factor
+        TCanvas &c13 = fDisplay->AddTab("Phe's");
+        c13.Divide(3,4);
+        
+        CamDraw(c13, 1, 3, disp5, 2, 1);
+        CamDraw(c13, 2, 3, disp6, 2, 1);
+        CamDraw(c13, 3, 3, disp7, 2, 1);
+        
+        // QE's
+        TCanvas &c14 = fDisplay->AddTab("QE's");
+        c14.Divide(4,4);
+        
+        CamDraw(c14, 1, 4, disp8,  2, 1);
+        CamDraw(c14, 2, 4, disp9,  2, 1);
+        CamDraw(c14, 3, 4, disp10, 2, 1);
+        CamDraw(c14, 4, 4, disp11, 2, 1);
+        
+        // Defects
+        TCanvas &c15 = fDisplay->AddTab("Defect");
+        c15.Divide(5,2);
+        
+        CamDraw(c15, 1, 5, disp23, 0);
+        CamDraw(c15, 2, 5, disp24, 0);
+        CamDraw(c15, 3, 5, disp25, 0);
+        CamDraw(c15, 4, 5, disp26, 0);
+        CamDraw(c15, 5, 5, disp27, 0);
+        
+        // Abs. Times
+        TCanvas &c16 = fDisplay->AddTab("Abs. Times");
+        c16.Divide(2,3);
+        
+        CamDraw(c16, 1, 2, disp28, 2);
+        CamDraw(c16, 2, 2, disp29, 1);
+
+        if (fRelTimes)
+          {
+            // Rel. Times
+            TCanvas &c17 = fDisplay->AddTab("Rel. Times");
+            c17.Divide(2,4);
+            
+            CamDraw(c17, 1, 2, disp30, 2, 1);
+            CamDraw(c17, 2, 2, disp31, 2, 1);
+          }
+        
+        return;
+      }
+    
+    if (fDisplayType == kFullDisplay)
+      {
+
+        MHCalibrationCam *cam = (MHCalibrationCam*)plist.FindObject("MHCalibrationChargeCam");
+
+        for (Int_t aidx=0;aidx<cam->GetAverageAreas();aidx++)
+          {
+            cam->GetAverageHiGainArea(aidx).DrawClone("all");
+            cam->GetAverageLoGainArea(aidx).DrawClone("all");
+          }
+        
+        for (Int_t sector=1;sector<cam->GetAverageSectors();sector++)
+          {
+            cam->GetAverageHiGainSector(sector).DrawClone("all");
+            cam->GetAverageLoGainSector(sector).DrawClone("all");
+          }
+
+        // Charges
+        TCanvas &c21 = fDisplay->AddTab("Fit.Charge");
+        c21.Divide(2, 4);
+        
+        CamDraw(c21, 1, 2, disp1, 2, 1);
+        CamDraw(c21, 2, 2, disp2, 2, 1);
+        
+        // Reduced Sigmas
+        TCanvas &c23 = fDisplay->AddTab("Red.Sigma");
+        c23.Divide(2,4);
+        
+        CamDraw(c23, 1, 2, disp3, 2, 1);
+        CamDraw(c23, 2, 2, disp4, 2, 1);
+        
+        //  F-Factor
+        TCanvas &c24 = fDisplay->AddTab("Phe's");
+        c24.Divide(3,4);
+        
+        CamDraw(c24, 1, 3, disp5, 2, 1);
+        CamDraw(c24, 2, 3, disp6, 2, 1);
+        CamDraw(c24, 3, 3, disp7, 2, 1);
+        
+        // QE's
+        TCanvas &c25 = fDisplay->AddTab("QE's");
+        c25.Divide(4,4);
+        
+        CamDraw(c25, 1, 4, disp8,  2, 1);
+        CamDraw(c25, 2, 4, disp9,  2, 1);
+        CamDraw(c25, 3, 4, disp10, 2, 1);
+        CamDraw(c25, 4, 4, disp11, 2, 1);
+        
+        // Validity
+        TCanvas &c26 = fDisplay->AddTab("Valid");
+        c26.Divide(4,2);
+        
+        CamDraw(c26, 1, 4, disp12, 0);
+        CamDraw(c26, 2, 4, disp13, 0);
+        CamDraw(c26, 3, 4, disp14, 0);
+        CamDraw(c26, 4, 4, disp15, 0);
+        
+        // Other info
+        TCanvas &c27 = fDisplay->AddTab("HiLoGain");
+        c27.Divide(3,3);
+        
+        CamDraw(c27, 1, 3, disp16, 0);
+        CamDraw(c27, 2, 3, disp17, 1);
+        CamDraw(c27, 3, 3, disp18, 1);
+        
+        // Pickup
+        TCanvas &c28 = fDisplay->AddTab("Pickup");
+        c28.Divide(4,2);
+        
+        CamDraw(c28, 1, 4, disp19, 0);
+        CamDraw(c28, 2, 4, disp20, 0);
+        CamDraw(c28, 3, 4, disp21, 0);
+        CamDraw(c28, 4, 4, disp22, 0);
+        
+        // Defects
+        TCanvas &c29 = fDisplay->AddTab("Defect");
+        c29.Divide(5,2);
+        
+        CamDraw(c29, 1, 5, disp23, 0);
+        CamDraw(c29, 2, 5, disp24, 0);
+        CamDraw(c29, 3, 5, disp25, 0);
+        CamDraw(c29, 4, 5, disp26, 0);
+        CamDraw(c29, 5, 5, disp27, 0);
+        
+        // Abs. Times
+        TCanvas &c30 = fDisplay->AddTab("Abs. Times");
+        c30.Divide(2,3);
+        
+        CamDraw(c30, 1, 2, disp28, 2);
+        CamDraw(c30, 2, 2, disp29, 1);
+
+        if (fRelTimes)
+          {
+            // Rel. Times
+            TCanvas &c31 = fDisplay->AddTab("Rel. Times");
+            c31.Divide(3,4);
+            
+            CamDraw(c31, 1, 3, disp30, 2, 1);
+            CamDraw(c31, 2, 3, disp31, 2, 1);
+            CamDraw(c31, 3, 3, disp32, 4, 1);
+
+            // Time Defects
+            TCanvas &c32 = fDisplay->AddTab("Time Def.");
+            c32.Divide(2,2);
+            
+            CamDraw(c32, 1, 2, disp33,0);
+            CamDraw(c32, 2, 2, disp34,0);
+
+            MHCalibrationCam *cam = (MHCalibrationCam*)plist.FindObject("MHCalibrationRelTimeCam");
+            
+            for (Int_t aidx=0;aidx<cam->GetAverageAreas();aidx++)
+              {
+                cam->GetAverageHiGainArea(aidx).DrawClone("fourierevents");
+                cam->GetAverageLoGainArea(aidx).DrawClone("fourierevents");
+              }
+            
+            for (Int_t sector=1;sector<cam->GetAverageSectors();sector++)
+              {
+                cam->GetAverageHiGainSector(sector).DrawClone("fourierevents");
+                cam->GetAverageLoGainSector(sector).DrawClone("fourierevents");
+              }
+            
+          }
+
+        return;
+      }
+}
+
+// --------------------------------------------------------------------------
+//
+// Draw a projection of MHCamera onto the y-axis values. Depending on the 
+// variable fit, the following fits are performed:
+//
+// 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)
+//
+// Moreover, sectors 6,1 and 2 of the camera and sectors 3,4 and 5 are 
+// drawn separately, for inner and outer pixels.
+//
+void MJCalibration::DrawProjection(MHCamera *obj, Int_t fit) const
+{
+  
+  TH1D *obj2 = (TH1D*)obj->Projection(obj->GetName());
+  obj2->SetDirectory(0);
+  obj2->Draw();
+  obj2->SetBit(kCanDelete);
+  
+  if (obj->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] = obj->ProjectionS(s0, inner, "Sector 6-1-2 Inner");
+      half[1] = obj->ProjectionS(s1, inner, "Sector 3-4-5 Inner");
+      half[2] = obj->ProjectionS(s0, outer, "Sector 6-1-2 Outer");
+      half[3] = obj->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.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 MJCalibration::DrawRadialProfile(MHCamera *obj) const
+{
+  
+  TProfile *obj2 = (TProfile*)obj->RadialProfile(obj->GetName());
+  obj2->SetDirectory(0);
+  obj2->Draw();
+  obj2->SetBit(kCanDelete);
+  
+  if (obj->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] = obj->RadialProfileS(s0, inner,Form("%s%s",obj->GetName(),"Inner"));
+      half[1] = obj->RadialProfileS(s0, outer,Form("%s%s",obj->GetName(),"Outer"));
+      
+      for (Int_t i=0; i<2; i++)
+        {
+          Double_t min = obj->GetGeomCam().GetMinRadius(i);
+          Double_t max = obj->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);
+        }
+    }
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Retrieve the output file written by WriteResult()
+// 
+TString MJCalibration::GetOutputFile() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F1.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Call the ProcessFile(MPedestalCam)
+// 
+Bool_t MJCalibration::Process(MPedestalCam &pedcam)
+{
+    if (!ReadCalibrationCam())
+        return ProcessFile(pedcam);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Execute the task list and the eventloop:
+//
+// - Check if there are fRuns, 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 fRelTimes is chosen)
+//   5) MBadPixelsCam         (fBadPixels)
+//   6) MCalibrationChargePINDiode
+//   7) MCalibrationChargeBlindPix
+// - Put into the MTaskList:
+//   1)  MReadMarsFile
+//   2)  MBadPixelsMerge
+//   3)  MGeomApply
+//   4)  MExtractSignal, MExtractSignal2 or MExtractSignal3, depending on fExtractorLevel
+//   5)  MExtractPINDiode
+//   6)  MExtractBlindPixel
+//   7)  MArrivalTimeCalc, MArrivalTimeCalc2, depending on fArrivalTimeLevel (only if flag fRelTimes is chosen)
+//   8)  MContinue(MFCosmics)
+//   9)  MFillH("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode")
+//   10) MFillH("MHCalibrationChargeBlindPix", "MExtractedSignalBlindPixel")
+//   11) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam")
+//   12) MFillH("MHCalibrationChargeCam",      "MExtractedSignalCam")
+//   13) MCalibrationChargeCalc
+//   14) MFillH("MHCalibrationRelTimeCam",     "MArrivalTimeCam") (only if flag fRelTimes is chosen)
+// - Execute MEvtLoop
+// - DisplayResult()
+// - WriteResult()
+//
+Bool_t MJCalibration::ProcessFile(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 MCalibrationCam from Runs " << fRuns->GetRunsAsString() << endl;
+  *fLog << endl;
+  
+  MReadMarsFile read("Events");
+  read.DisableAutoScheme();
+  static_cast<MRead&>(read).AddFiles(*fRuns);
+  
+  MCalibrationChargePINDiode pindiode;
+  MCalibrationChargeBlindPix blindpix;
+  
+  // Setup Tasklist
+  MParList plist;
+  plist.AddToList(&pedcam);
+  plist.AddToList(&fBadPixels);
+  plist.AddToList(&fQECam);
+  plist.AddToList(&fCalibrationCam);
+  plist.AddToList(&pindiode);
+  plist.AddToList(&blindpix);
+
+  MTaskList tlist;
+  plist.AddToList(&tlist);
+  
+  MGeomApply               apply;
+  //    MBadPixelsMerge          merge(&fBadPixels);
+  MExtractPINDiode         pinext;
+  MExtractBlindPixel       blindext;
+  MExtractSignal           extract1; 
+  MExtractSignal2          extract2;
+  MExtractSignal3          extract3;
+  MArrivalTimeCalc         tmecalc1;
+  MArrivalTimeCalc2        tmecalc2;
+  MCalibrationChargeCalc   calcalc;
+  
+  // 
+  // As long as there are no DM's, have to colour by hand 
+  //
+  calcalc.SetPulserColor(fColor);
+  
+  MFillH fillpin("MHCalibrationChargePINDiode", "MExtractedSignalPINDiode");
+  MFillH fillbnd("MHCalibrationChargeBlindPix", "MExtractedSignalBlindPixel");
+  MFillH fillcam("MHCalibrationChargeCam",      "MExtractedSignalCam");
+  MFillH filltme("MHCalibrationRelTimeCam",     "MArrivalTimeCam");
+  fillpin.SetNameTab("PINDiode");
+  fillbnd.SetNameTab("BlindPix");
+  fillcam.SetNameTab("Charge");
+  filltme.SetNameTab("RelTimes");
+  
+  
+  // 
+  // Apply a filter against cosmics
+  // (will have to be needed in the future
+  // when the calibration hardware-trigger is working)
+  // 
+  MFCosmics cosmics;
+  MContinue cont(&cosmics);
+  
+  tlist.AddToList(&read);
+  //    tlist.AddToList(&merge);
+  tlist.AddToList(&apply);
+
+  if (fExtractorLevel <= 1)
+    tlist.AddToList(&extract1);
+  else if (fExtractorLevel == 2) 
+    tlist.AddToList(&extract2);
+  else if (fExtractorLevel == 3) 
+    tlist.AddToList(&extract3);
+  else
+    {
+      *fLog << err << GetDescriptor() 
+            << ": No valid Signal extractor has been chosen, have only: " << fExtractorLevel 
+            << " aborting..." << endl;
+      return kFALSE;
+    }
+  
+
+  tlist.AddToList(&pinext);  
+  tlist.AddToList(&blindext);
+  
+  if (fRelTimes)
+    {
+      plist.AddToList(&fRelTimeCam);
+      if (fArrivalTimeLevel <= 1)
+        tlist.AddToList(&tmecalc1);
+      else if (fArrivalTimeLevel == 2) 
+        tlist.AddToList(&tmecalc2);
+      else
+        {
+          *fLog << err << GetDescriptor() 
+                << ": No valid Signal ArrivalTime Level has been chosen, have only: " << fArrivalTimeLevel 
+                << " aborting..." << endl;
+          return kFALSE;
+        }
+    }
+
+  tlist.AddToList(&cont);
+  tlist.AddToList(&fillcam);
+  tlist.AddToList(&fillpin);
+  tlist.AddToList(&fillbnd);
+  tlist.AddToList(&calcalc);
+
+  if (fRelTimes)
+    tlist.AddToList(&filltme);
+  
+  // 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Read the following containers from GetOutputFile()
+// - MCalibrationChargeCam
+// - MCalibrationQECam
+// - MBadPixelsCam
+//
+Bool_t MJCalibration::ReadCalibrationCam()
+{
+    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("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 path for output files, written by WriteResult()
+// 
+void MJCalibration::SetOutputPath(const char *path)
+{
+    fOutputPath = path;
+    if (fOutputPath.EndsWith("/"))
+        fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+
+// --------------------------------------------------------------------------
+//
+// Write the result into the output file GetOutputFile(), if fOutputPath exists.
+// 
+// The following containers are written:
+// - MStatusDisplay
+// - MCalibrationChargeCam
+// - MCalibrationQECam
+// - MBadPixelsCam
+//
+Bool_t MJCalibration::WriteResult()
+{
+    if (fOutputPath.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 (fCalibrationCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationChargeCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fQECam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MCalibrationQECam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fBadPixels.Write()<=0)
+    {
+        *fLog << err << "Unable to write MBadPixelsCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJCalibration.h	(revision 3781)
@@ -0,0 +1,92 @@
+#ifndef MARS_MJCalibration
+#define MARS_MJCalibration
+
+#ifndef MARS_MCalibrationChargeCam
+#include "MCalibrationChargeCam.h"
+#endif
+#ifndef MARS_MCalibrationRelTimeCam
+#include "MCalibrationRelTimeCam.h"
+#endif
+#ifndef MARS_MCalibrationQECam
+#include "MCalibrationQECam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+class TCanvas;
+class MHCamera;
+class MCamEvent;
+class MRunIter;
+class MParList;
+class MPedestalCam;
+class MJCalibration : public MParContainer
+{
+private:
+
+  TString fOutputPath;                                     // Path to the output files
+  
+  MRunIter *fRuns;                                         // Calibration files
+  
+  MBadPixelsCam          fBadPixels;                       // Bad Pixels cam, can be set from previous runs
+  MCalibrationChargeCam  fCalibrationCam;                  // Calibration conversion factors FADC2Phe
+  MCalibrationQECam      fQECam;                           // Quantum efficiency, can be set from previous runs
+  MCalibrationRelTimeCam fRelTimeCam;                      // Calibration constants rel. times
+
+  MCalibrationCam::PulserColor_t fColor;                   // Colour of the pulsed LEDs
+
+  enum  Display_t   { kFullDisplay, kDataCheck, kNormalDisplay }; // Possible Display types
+  
+  Display_t fDisplayType;                                  // Chosen Display type
+
+  Bool_t fRelTimes;                                        // Flag if relative times have to be calibrated
+  UInt_t fExtractorLevel;                                  // Level signal extractor (e.g. MExtractSignal2) 
+  UInt_t fArrivalTimeLevel;                                // Level arr. time extractor (e.g. MArrivalTimeCalc2)
+  
+  void DrawProjection   ( MHCamera *obj, Int_t fit) const; // Draw projection of pixels values
+  void DrawRadialProfile( MHCamera *obj)            const; // Draw projection of pixels values onto camera radius
+  void CamDraw(TCanvas &c, const Int_t x, const Int_t y, const MHCamera &cam1,
+               const Int_t fit, const Int_t rad=0);        // Draw histograms into the MStatusDisplay
+  
+  void   DisplayResult(MParList &plist);
+  Bool_t WriteResult();
+
+public:
+
+  MJCalibration(const char *name=NULL, const char *title=NULL);
+  
+  void SetInput(MRunIter *iter) { fRuns=iter; }
+  void SetOutputPath(const char *path=".");
+  
+  TString GetOutputFile() const;
+
+  MCalibrationChargeCam  &GetCalibrationCam()     { return fCalibrationCam; }  
+  MCalibrationRelTimeCam &GetRelTimeCam()         { return fRelTimeCam;     }
+  MCalibrationQECam      &GetQECam()              { return fQECam;          }    
+  const MBadPixelsCam    &GetBadPixels() const    { return fBadPixels;      }
+  
+  void SetBadPixels(const MBadPixelsCam &bad)    { bad.Copy(fBadPixels);   }
+  void SetQECam    (const MCalibrationQECam &qe) { qe.Copy(fQECam);        }    
+  void SetColor    (const MCalibrationCam::PulserColor_t color) { fColor = color; }
+
+  // Displays
+  void SetFullDisplay()    { fDisplayType = kFullDisplay;   }
+  void SetDataCheck()      { fDisplayType = kDataCheck;     }
+  void SetNormalDisplay()  { fDisplayType = kNormalDisplay; }
+
+  // Rel. Time
+  void SetRelTimeCalibration(const Bool_t b=kTRUE) { fRelTimes         = b; }
+
+  // Extractors
+  void SetExtractorLevel    (const UInt_t i=1    ) { fExtractorLevel   = i; }
+  void SetArrivalTimeLevel  (const UInt_t i=1    ) { fArrivalTimeLevel = i; }  
+      
+  
+  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-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.cc	(revision 3781)
@@ -0,0 +1,505 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "MHCamera.h"
+
+#include "MPedestalCam.h"
+#include "MCalibrationChargeCam.h"
+#include "MHCamEvent.h"
+
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MExtractSignal.h"
+#include "MFillH.h"
+#include "MCalibrate.h"
+#include "MPedPhotCalc.h"
+#include "MWriteRootFile.h"
+
+#include "MJExtractSignal.h"
+#include "MStatusDisplay.h"
+
+
+ClassImp(MJExtractSignal);
+
+using namespace std;
+
+MJExtractSignal::MJExtractSignal(const char *name, const char *title) : fRuns(0)
+{
+    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, "UPDATE");
+
+    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);
+    MExtractSignal  extract;
+
+    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("MRawEvtHeader",       "Events");
+    write.AddContainer("MPedestalCam",        "RunHeaders");
+    write.AddContainer("MRawRunHeader",       "RunHeaders");
+    write.AddContainer("MBadPixelsCam",       "RunHeaders");
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&merge);
+    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;
+}
+
+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)
+{
+    if (!ReadPedPhotCam())
+        return ProcessFileP(pedcam, calcam);
+
+    return kTRUE;
+}
+
+Bool_t MJExtractSignal::ProcessFileP(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;
+    }
+
+    *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(&fPedPhotCam);
+    plist.AddToList(&fBadPixels);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply      apply; // Only necessary to craete geometry
+    MBadPixelsMerge merge(&fBadPixels);
+    MExtractSignal  extract;
+    MCalibrate      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;
+    MCalibrate     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;
+    MCalibrate     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-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJExtractSignal.h	(revision 3781)
@@ -0,0 +1,57 @@
+#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 MJExtractSignal : public MParContainer
+{
+private:
+    TString fOutputPath;
+
+    MRunIter *fRuns;
+
+    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);
+
+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 SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+
+    Bool_t ProcessD(MPedestalCam &pedcam);
+    Bool_t ProcessP(MPedestalCam &pedcam, MCalibrationChargeCam &calcam);
+
+    ClassDef(MJExtractSignal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJPedestal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJPedestal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJPedestal.cc	(revision 3781)
@@ -0,0 +1,386 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+//  MJPedestal
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MJPedestal.h"
+
+#include <TF1.h>
+#include <TFile.h>
+#include <TStyle.h>
+#include <TString.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 "MStatusDisplay.h"
+
+#include "MGeomCam.h"
+#include "MHCamera.h"
+#include "MPedestalCam.h"
+#include "MBadPixelsCam.h"
+
+#include "MReadMarsFile.h"
+#include "MGeomApply.h"
+#include "MBadPixelsMerge.h"
+#include "MPedCalcPedRun.h"
+
+ClassImp(MJPedestal);
+
+using namespace std;
+
+MJPedestal::MJPedestal(const char *name, const char *title) : fRuns(0)
+{
+    fName  = name  ? name  : "MJPedestal";
+    fTitle = title ? title : "Tool to create a pedestal file (MPedestalCam)";
+}
+
+TString MJPedestal::GetOutputFile() const
+{
+    if (!fRuns)
+        return "";
+
+    return Form("%s/%s-F0.root", (const char*)fOutputPath, (const char*)fRuns->GetRunsAsFileName());
+}
+
+Bool_t MJPedestal::ReadPedestalCam()
+{
+    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 (fPedestalCam.Read()<=0)
+    {
+        *fLog << err << "Unable to read 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;
+}
+
+void MJPedestal::DrawProjection(MHCamera *obj1, Int_t fit) const
+{
+    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 MJPedestal::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");
+
+    obj1->AddNotify(&fPedestalCam);
+
+    c.cd(x+y);
+    gPad->SetBorderMode(0);
+    obj1->Draw();
+
+    c.cd(x+2*y);
+    gPad->SetBorderMode(0);
+    DrawProjection(obj1, fit);
+}
+
+void MJPedestal::DisplayResult(MParList &plist)
+{
+    if (!fDisplay)
+        return;
+
+    //
+    // Update display
+    //
+    TString title = fDisplay->GetTitle();
+    title += "--  Pedestal ";
+    title += fRuns->GetRunsAsString();
+    title += "  --";
+    fDisplay->SetTitle(title);
+
+    //
+    // Get container from list
+    //
+    MGeomCam &geomcam = *(MGeomCam*)plist.FindObject("MGeomCam");
+
+    //
+    // Create container to display
+    //
+    MHCamera disp0(geomcam, "MPedestalCam;ped", "Pedestals");
+    MHCamera disp1(geomcam, "MPedestalCam;var", "Sigma Pedestal");
+
+    disp0.SetCamContent(fPedestalCam, 0);
+    disp0.SetCamError  (fPedestalCam, 1);
+
+    disp1.SetCamContent(fPedestalCam, 2);
+    disp1.SetCamError  (fPedestalCam, 3);
+
+    disp0.SetYTitle("P [fadc/slice]");
+    disp1.SetYTitle("\\sigma_{P} [fadc/slice]");
+
+    //
+    // Display data
+    //
+    TCanvas &c3 = fDisplay->AddTab("Pedestals");
+    c3.Divide(2,3);
+
+    CamDraw(c3, 1, 2, disp0, 0);
+    CamDraw(c3, 2, 2, disp1, 1);
+}
+
+Bool_t MJPedestal::WriteResult()
+{
+    if (fOutputPath.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 (fPedestalCam.Write()<=0)
+    {
+        *fLog << err << "Unable to write MPedestalCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    if (fBadPixels.Write()<=0)
+    {
+        *fLog << err << "Unable to write MBadPixelsCam to " << oname << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+void MJPedestal::SetOutputPath(const char *path)
+{
+    fOutputPath = path;
+    if (fOutputPath.EndsWith("/"))
+        fOutputPath = fOutputPath(0, fOutputPath.Length()-1);
+}
+
+Bool_t MJPedestal::Process()
+{
+    if (!ReadPedestalCam())
+        return ProcessFile();
+
+    return kTRUE;
+}
+
+Bool_t MJPedestal::ProcessFile()
+{
+    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 MPedestalCam from Runs " << fRuns->GetRunsAsString() << endl;
+    *fLog << endl;
+
+    MReadMarsFile read("Events");
+    read.DisableAutoScheme();
+    static_cast<MRead&>(read).AddFiles(*fRuns);
+
+    // Enable logging to file
+    //*fLog.SetOutputFile(lname, kTRUE);
+
+    // Setup Tasklist
+    MParList plist;
+    plist.AddToList(&fPedestalCam);
+    plist.AddToList(&fBadPixels);
+
+    MTaskList tlist;
+    plist.AddToList(&tlist);
+
+    MGeomApply      geomapl;
+    // MBadPixelsMerge merge(&fBadPixels);
+    //MExtractSignal sigcalc;
+    MPedCalcPedRun  pedcalc;
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&geomapl);
+    //    tlist.AddToList(&merge);
+    //tlist.AddToList(&sigcalc);
+    tlist.AddToList(&pedcalc);
+
+    //
+    // Execute 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-8-4/MagicSoft/Mars/mjobs/MJPedestal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJPedestal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/MJPedestal.h	(revision 3781)
@@ -0,0 +1,53 @@
+#ifndef MARS_MJPedestal
+#define MARS_MJPedestal
+
+#ifndef MARS_MPedestalCam
+#include "MPedestalCam.h"
+#endif
+#ifndef MARS_MBadPixelsCam
+#include "MBadPixelsCam.h"
+#endif
+
+
+class TCanvas;
+class MParList;
+class MRunIter;
+class MHCamera;
+
+class MJPedestal : public MParContainer
+{
+private:
+    TString fOutputPath;
+
+    MRunIter *fRuns;
+
+    MPedestalCam  fPedestalCam;
+    MBadPixelsCam fBadPixels;
+
+    Bool_t ReadPedestalCam();
+    Bool_t WriteResult();
+    
+    void   DrawProjection(MHCamera *obj1, Int_t fit) const;
+    void   CamDraw(TCanvas &c, Int_t x, Int_t y, MHCamera &cam1, Int_t fit);
+    void   DisplayResult(MParList &plist);
+
+public:
+    MJPedestal(const char *name=NULL, const char *title=NULL);
+
+    void SetOutputPath(const char *path=".");
+    void SetInput(MRunIter *iter) { fRuns=iter; }
+
+    TString GetOutputFile() const;
+
+    MPedestalCam &GetPedestalCam() { return fPedestalCam; }
+    const MBadPixelsCam &GetBadPixels() const { return fBadPixels; }
+
+    void SetBadPixels(const MBadPixelsCam &bad) { bad.Copy(fBadPixels); }
+
+    Bool_t ProcessFile();
+    Bool_t Process();
+
+    ClassDef(MJPedestal, 0) // Tool to create a pedestal file (MPedestalCam)
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mjobs/Makefile	(revision 3781)
@@ -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  = Jobs
+
+#
+# Library name to creatre
+#
+LIB   = mjobs.a
+
+#
+#  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../mfilter -I../manalysis -I../mhist -I../mcalib \
+           -I../mbadpixels -I../msignal
+
+#manalysis: MChisqEval (MParameters)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MJPedestal.cc \
+           MJCalibration.cc \
+           MJExtractSignal.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MAnalysis.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MAnalysis.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MAnalysis.cc	(revision 3781)
@@ -0,0 +1,327 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "MBlindPixelCalc.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-8-4/MagicSoft/Mars/mmain/MAnalysis.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MAnalysis.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MAnalysis.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MBrowser.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MBrowser.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MBrowser.cc	(revision 3781)
@@ -0,0 +1,603 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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)
+    {
+        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);
+        // Note necessary - deleted in ~TGLBContainer: fList->Add(laylb);
+        fList->Add(entry);
+    }
+
+    //
+    // 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-8-4/MagicSoft/Mars/mmain/MBrowser.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MBrowser.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MBrowser.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MCameraDisplay.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MCameraDisplay.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MCameraDisplay.cc	(revision 3781)
@@ -0,0 +1,99 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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);
+
+    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, "ped.root", "cal.root");
+            return kTRUE;
+        }
+        return kTRUE;
+    }
+
+    return MBrowser::ProcessMessage(msg, parm1, parm2);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MCameraDisplay.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MCameraDisplay.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MCameraDisplay.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MDataCheck.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MDataCheck.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MDataCheck.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MDataCheck.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MDataCheck.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MDataCheck.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MEventDisplay.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MEventDisplay.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MEventDisplay.cc	(revision 3781)
@@ -0,0 +1,667 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 <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 <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 "MCerPhotAnal2.h"        // MCerPhotAnal2
+#include "MImgCleanStd.h"         // MImgCleanStd
+#include "MHillasCalc.h"          // MHillasCalc
+#include "MHillasSrcCalc.h"       // MHillasSrcCalc
+#include "MBlindPixelCalc.h"      // MBlindPixelCalc
+#include "MArrivalTimeCalc.h"     // MArrivalTimeCalc
+#include "MFillH.h"               // MFillH
+#include "MExtractSignal.h"       // MExtractsignal
+#include "MMcCalibrationUpdate.h" // MMcCalibrationUpdate
+#include "MCalibrate.h"           // MCalibrate
+
+//
+// Container
+//
+#include "MHillas.h"               // MHillas::Print(const MGeomCam&)
+#include "MHillasExt.h"            // MHillasExt::Print(const MGeomCam&)
+#include "MHillasSrc.h"            // MHillasSrc::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
+
+ClassImp(MEventDisplay);
+
+// --------------------------------------------------------------------------
+//
+//  Constructor.
+//
+MEventDisplay::MEventDisplay(const char *fname, const char *pname, const char *cname) : MStatusDisplay()
+{
+    //
+    // Setup Task list for hillas calculation
+    //
+    SetupTaskList("Events", fname, pname, cname);
+
+    //
+    // 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
+    //
+    ReadFirstEvent();
+}
+
+// --------------------------------------------------------------------------
+//
+//  Destructor: PostProcess eventloop, delete eventloop with all containers
+//
+MEventDisplay::~MEventDisplay()
+{
+    fEvtLoop->PostProcess();
+    delete fEvtLoop;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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,
+                                  const char *pname, const char *cname)
+{
+    MCalibrationChargeCam *ccam=0;
+    MPedPhotCam           *pcam=0;
+
+    MBadPixelsCam *badpix = new MBadPixelsCam;
+
+    TFile file(pname, "READ");
+    if (!file.IsZombie())
+        pcam = new MPedPhotCam;
+    if (pcam)
+    {
+        if (pcam->Read()<=0)
+        {
+            delete pcam;
+            pcam = NULL;
+        }
+
+        if (file.FindKey("MBadPixelsCam"))
+        {
+            MBadPixelsCam bad;
+            if (bad.Read()>0)
+                badpix->Merge(bad);
+        }
+    }
+    file.Close();
+    file.Open(cname, "READ");
+    if (!file.IsZombie())
+        ccam = new MCalibrationChargeCam;
+    if (ccam)
+    {
+        if (ccam->Read()<=0)
+        {
+            delete ccam;
+            ccam = NULL;
+        }
+
+        if (file.FindKey("MBadPixelsCam"))
+        {
+            MBadPixelsCam bad;
+            if (bad.Read()>0)
+                badpix->Merge(bad);
+        }
+    }
+    file.Close();
+
+    //
+    // 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);
+    if (pcam)
+        plist->AddToList(pcam);
+    if (ccam)
+        plist->AddToList(ccam);
+
+    fEvtLoop = new MEvtLoop;
+    fEvtLoop->SetOwner();
+    fEvtLoop->SetParList(plist);
+
+    MHEvent *evt1 = new MHEvent(MHEvent::kEvtSignalRaw);
+    MHEvent *evt2 = new MHEvent(MHEvent::kEvtSignalRaw);
+    MHEvent *evt3 = new MHEvent(MHEvent::kEvtPedestal);
+    MHEvent *evt4 = new MHEvent(MHEvent::kEvtPedestalRMS);
+    MHEvent *evt5 = new MHEvent(MHEvent::kEvtRelativeSignal);
+    MHEvent *evt6 = new MHEvent(MHEvent::kEvtCleaningLevels);
+    MHEvent *evt7 = new MHEvent(MHEvent::kEvtIdxMax);
+    MHEvent *evt8 = new MHEvent(MHEvent::kEvtArrTime);
+
+    evt1->SetName("Signal");
+    evt2->SetName("Cleaned");
+    evt3->SetName("Pedestal");
+    evt4->SetName("PedRMS");
+    evt5->SetName("Signal/PedRMS");
+    evt6->SetName("CleanLevels");
+    evt7->SetName("Max Slice Idx");
+    evt8->SetName("Arrival Time");
+
+    // This makes sure, that the containers are deleted...
+    plist->AddToList(evt1);
+    plist->AddToList(evt2);
+    plist->AddToList(evt3);
+    plist->AddToList(evt4);
+    plist->AddToList(evt5);
+    plist->AddToList(evt6);
+    plist->AddToList(evt7);
+    plist->AddToList(evt8);
+
+    MCerPhotAnal2     *nanal = new MCerPhotAnal2;
+    MFillH            *fill1 = new MFillH(evt1, "MCerPhotEvt", "MFillH1");
+    MImgCleanStd      *clean = new MImgCleanStd;
+    MFillH            *fill2 = new MFillH(evt2, "MCerPhotEvt", "MFillH2");
+    MFillH            *fill3 = new MFillH(evt3, "MPedPhotCam", "MFillH3");
+    MFillH            *fill4 = new MFillH(evt4, "MPedPhotCam", "MFillH4");
+    MFillH            *fill5 = new MFillH(evt5, "MCameraData", "MFillH5");
+    MFillH            *fill6 = new MFillH(evt6, "MCameraData", "MFillH6");
+    MBlindPixelCalc   *blind = new MBlindPixelCalc;
+    MHillasCalc       *hcalc = new MHillasCalc;
+    MHillasSrcCalc    *scalc = new MHillasSrcCalc;
+
+    // If no pedestal or no calibration file is availble
+    if (!pcam || !ccam)
+    {
+        MFilter *f1=new MFDataMember("MRawRunHeader.fRunType", '>', 255.5);
+        MFilter *f2=new MFDataMember("MRawRunHeader.fRunType", '<', 255.5);
+        f1->SetName("MFMonteCarlo");
+        f2->SetName("MFRealData");
+
+        MMcPedestalCopy   *pcopy = new MMcPedestalCopy;
+        MMcPedestalNSBAdd *pdnsb = new MMcPedestalNSBAdd;
+
+        MExtractSignal* extra = new MExtractSignal();
+	extra->SetRange(5, 10, 5, 10);
+	extra->SetSaturationLimit(240);
+
+        MMcCalibrationUpdate* mcupd = new MMcCalibrationUpdate;
+        mcupd->SetOuterPixelsGainScaling(kFALSE);
+
+        MCalibrate* mccal = new MCalibrate;
+        mccal->SetCalibrationMode(MCalibrate::kFfactor);
+
+        // MC
+        extra->SetFilter(f1);
+        mcupd->SetFilter(f1);
+        mccal->SetFilter(f1);
+
+        // Data
+        nanal->SetFilter(f2);
+
+        // TaskList
+        tlist->AddToList(f1);
+        tlist->AddToList(f2);
+        tlist->AddToList(pcopy);
+        tlist->AddToList(pdnsb);
+
+        tlist->AddToList(extra);
+        tlist->AddToList(mcupd);
+        tlist->AddToList(mccal);
+
+        tlist->AddToList(nanal);
+    }
+    else
+    {
+        MCalibrate* calib = new MCalibrate;
+        tlist->AddToList(calib);
+    }
+
+    tlist->AddToList(fill1);
+    tlist->AddToList(clean);
+    tlist->AddToList(fill2);
+    tlist->AddToList(fill3);
+    tlist->AddToList(fill4);
+    tlist->AddToList(fill5);
+    tlist->AddToList(fill6);
+    tlist->AddToList(blind);
+    tlist->AddToList(hcalc);
+    tlist->AddToList(scalc);
+    if (!pcam || !ccam)
+    {
+        MArrivalTimeCalc  *tcalc = new MArrivalTimeCalc;
+        MFillH            *fill7 = new MFillH(evt7, "MRawEvtData",     "MFillH7");
+        MFillH            *fill8 = new MFillH(evt8, "MArrivalTimeCam", "MFillH8");
+        tlist->AddToList(tcalc);
+        tlist->AddToList(fill7);
+        tlist->AddToList(fill8);
+    }
+
+    //
+    // Now distribute Display to all tasks
+    //
+    tlist->SetDisplay(this);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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;
+        }
+
+        if (!tlist->Process())
+            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);
+    ((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()
+{
+    if (!fEvtLoop->PreProcess())
+        return;
+
+    //
+    // 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 *hillas = plist->FindObject("MHillas");
+    for (int i=1; i<7;i++)
+    {
+        TCanvas *c = GetCanvas(i);
+        c->GetPad(1)->cd(1);
+        hillas->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)));
+            }
+            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-8-4/MagicSoft/Mars/mmain/MEventDisplay.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MEventDisplay.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MEventDisplay.h	(revision 3781)
@@ -0,0 +1,57 @@
+#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,
+                       const char *pname=0, const char *cname=0);
+
+    void ReadFirstEvent();
+    void ReadinEvent(Int_t dir=0);
+
+    Bool_t ProcessMessage(Long_t msg, Long_t parm1, Long_t parm2);
+
+public:
+    MEventDisplay(const char *fname, const char *pname=0, const char *cname=0);
+    ~MEventDisplay();
+
+    ClassDef(MEventDisplay, 0) // Display for camera images (cerenkov events)
+};
+
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MGDisplayAdc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MMars.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMars.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMars.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MMars.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMars.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMars.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MMonteCarlo.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMonteCarlo.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMonteCarlo.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MMonteCarlo.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMonteCarlo.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MMonteCarlo.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.cc	(revision 3781)
@@ -0,0 +1,226 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 "MBlindPixelCalc.h"     // MBlindPixelCalc
+#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-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDisplay.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MOnlineDump.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDump.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDump.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MOnlineDump.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDump.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MOnlineDump.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmain/MainIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MainIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MainIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MainLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MainLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/MainLinkDef.h	(revision 3781)
@@ -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 MBrowser+;
+
+#pragma link C++ class MMars+;
+#pragma link C++ class MAnalysis+;
+#pragma link C++ class MDataCheck+;
+#pragma link C++ class MMonteCarlo+;
+
+#pragma link C++ class MCameraDisplay+;
+#pragma link C++ class MEventDisplay+;
+#pragma link C++ class MOnlineDisplay+;
+#pragma link C++ class MOnlineDump+;
+
+#pragma link C++ class MGDisplayAdc+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmain/Makefile	(revision 3781)
@@ -0,0 +1,59 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Main
+
+#
+# Library name to creatre
+#
+LIB   = mmain.a
+
+#
+#  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
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MBrowser.cc \
+	   MDataCheck.cc \
+	   MMars.cc \
+           MAnalysis.cc \
+	   MMonteCarlo.cc \
+           MGDisplayAdc.cc \
+	   MEventDisplay.cc \
+	   MOnlineDisplay.cc \
+	   MOnlineDump.cc \
+           MCameraDisplay.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.cc	(revision 3781)
@@ -0,0 +1,223 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MHMcCollectionAreaCalc
+//
+//  Remark: The initialization is mainly done in the ReInit function.
+//          Please make sure, that you don't use MReadTree when processing
+//          a file. Use a 'ReInit'-calling task like MReadMarsFile
+//
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MMcCollectionAreaCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MMcEvt.hxx"
+#include "MMcTrig.hxx"
+#include "MMcRunHeader.hxx"
+#include "MMcCorsikaRunHeader.h"
+
+#include "MHMcCollectionArea.h"
+
+ClassImp(MMcCollectionAreaCalc);
+
+using namespace std;
+
+MMcCollectionAreaCalc::MMcCollectionAreaCalc(const char *input,
+                                             const char *name, const char *title)
+{
+    fName  = name  ? name  : "MMcCollectionAreaCalc";
+    fTitle = title ? title : "Task to calculate the collection area";
+
+    fObjName = input ? input : "MMcTrig";
+    AddToBranchList(Form("%s.fNumFirstLevel", input));
+
+    AddToBranchList("MMcEvt.fEnergy");
+    AddToBranchList("MMcEvt.fImpact");
+
+    fCorsikaVersion           =  0;
+    fAllEvtsTriggered         =  kFALSE;
+    fTotalNumSimulatedShowers =  0;
+    fTheta                    = -1.;
+
+} 
+
+Int_t MMcCollectionAreaCalc::PreProcess (MParList *pList)
+{
+    // connect the raw data with this task
+
+    fMcEvt = (MMcEvt*)pList->FindObject("MMcEvt");
+    if (!fMcEvt)
+    {
+        *fLog << err << dbginf << "MMcEvt not found... exit." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Bool_t MMcCollectionAreaCalc::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;
+    }
+
+    fTotalNumSimulatedShowers += runheader->GetNumSimulatedShowers();
+    *fLog << inf << "Total Number of Simulated showers: " << fTotalNumSimulatedShowers << endl;
+
+
+    if (fTheta>=0 && fTheta!=runheader->GetTelesTheta())
+    {
+        *fLog << warn << dbginf << "Warning - Read files have different TelesTheta (";
+        *fLog << fTheta << ", " << runheader->GetTelesTheta() << ")..." << endl;
+    }
+    fTheta = runheader->GetTelesTheta();
+
+
+    if (fCorsikaVersion!=0 && fCorsikaVersion!=runheader->GetCorsikaVersion())
+        *fLog << warn << dbginf << "Warning - Read files have different Corsika versions..." << endl;
+    fCorsikaVersion = runheader->GetCorsikaVersion();
+
+
+    fAllEvtsTriggered |= runheader->GetAllEvtsTriggered();
+    *fLog << inf << "Only triggered events avail: " << (fAllEvtsTriggered?"yes":"no") << endl;
+
+
+    fCollArea = (MHMcCollectionArea*)plist->FindCreateObj("MHMcCollectionArea");
+    if (!fCollArea)
+        return kFALSE;
+
+    if (fAllEvtsTriggered)
+      {
+	//
+	// Calculate approximately the original number of events in each 
+	// energy bin:
+	//
+
+	const Float_t emin = corrunheader->GetELowLim();
+	const Float_t emax = corrunheader->GetEUppLim();
+	const Float_t expo = 1 + corrunheader->GetSlopeSpec();
+	const Float_t k = runheader->GetNumSimulatedShowers() / 
+	  (pow(emax,expo) - pow(emin,expo)) ;
+
+        TH2 &hall = *fCollArea->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 < emin || e2 > emax)
+	      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);
+	  }
+
+        return kTRUE;
+      }
+
+    fMcTrig = (MMcTrig*)plist->FindObject(fObjName);
+    if (!fMcTrig)
+    {
+        *fLog << err << dbginf << fObjName << " [MMcTrig] not found... exit." << endl;
+        return kFALSE;
+    }
+
+    return kTRUE;
+}
+
+Int_t MMcCollectionAreaCalc::Process()
+{
+    const Double_t energy = fMcEvt->GetEnergy();
+    const Double_t impact = fMcEvt->GetImpact()/100.;
+
+    //
+    // This happens for camera files created with Camera 0.5
+    //
+    if (TMath::IsNaN(impact))
+    {
+        *fLog << err << dbginf << "ERROR - Impact=NaN (Not a number)... abort." << endl;
+        return kERROR;
+    }
+
+    if (!fAllEvtsTriggered)
+    {
+        fCollArea->FillAll(energy, impact);
+
+        if (fMcTrig->GetFirstLevel() <= 0)
+            return kTRUE;
+    }
+
+    fCollArea->FillSel(energy, impact);
+
+    return kTRUE;
+}
+
+Int_t MMcCollectionAreaCalc::PostProcess()
+{ 
+    //
+    //   do the calculation of the effectiv area
+    //
+    *fLog << inf << "Calculation Collection Area..." << endl;
+
+    if (!fAllEvtsTriggered)
+        fCollArea->CalcEfficiency();
+    else
+    {
+        *fLog << inf << "Total number of showers: " << fTotalNumSimulatedShowers << endl;
+        fCollArea->CalcEfficiency2();
+    }
+
+    return kTRUE;
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcCollectionAreaCalc.h	(revision 3781)
@@ -0,0 +1,44 @@
+#ifndef MARS_MMcCollectionAreaCalc
+#define MARS_MMcCollectionAreaCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+#include <TH2.h>
+
+class MParList;
+class MMcEvt;
+class MMcTrig;
+class MHMcCollectionArea;
+
+class MMcCollectionAreaCalc : public MTask
+{
+private:
+    const MMcEvt  *fMcEvt;
+    const MMcTrig *fMcTrig;
+
+    MHMcCollectionArea *fCollArea;
+
+    TString fObjName;
+
+    UInt_t fTotalNumSimulatedShowers;
+    UInt_t fCorsikaVersion;
+    Bool_t fAllEvtsTriggered;
+    Float_t fTheta;
+
+    Bool_t ReInit(MParList *plist);
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MMcCollectionAreaCalc(const char *input=NULL,
+                          const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MMcCollectionAreaCalc, 0) // Task to calculate the collection area histogram
+};
+
+#endif 
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.cc	(revision 3781)
@@ -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): 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>
+!
+!   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  = evtloop->GetTaskList();
+
+    MParameterD     *eval = (MParameterD*)    plist->FindObject("MFitResult", "MParameterD");
+    MEnergyEstParam *eest = (MEnergyEstParam*)tlist->FindObject("MEnergyEstParam");
+
+    eest->SetCoeff(TArrayD(eest->GetNumCoeff(), par));
+
+    evtloop->Eventloop();
+
+    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-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcEnergyEst.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcThresholdCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTimeGenerate.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcTriggerRateCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.cc	(revision 3781)
@@ -0,0 +1,378 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MMcWeightEnergySpecCalc.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mmontecarlo/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/Makefile	(revision 3781)
@@ -0,0 +1,54 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = MonteCarlo
+
+#
+# Library name to creatre
+#
+LIB   = mmontecarlo.a
+
+#
+#  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
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MMcCollectionAreaCalc.cc \
+	   MMcThresholdCalc.cc \
+           MMcTimeGenerate.cc \
+	   MMcTriggerRateCalc.cc \
+	   MMcEnergyEst.cc \
+	   MMcWeightEnergySpecCalc.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o)
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mmontecarlo/MonteCarloLinkDef.h	(revision 3781)
@@ -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 MMcThresholdCalc+;
+#pragma link C++ class MMcTimeGenerate+;
+#pragma link C++ class MMcCollectionAreaCalc+;
+#pragma link C++ class MMcTriggerRateCalc+;
+#pragma link C++ class MMcEnergyEst+;
+#pragma link C++ class MMcWeightEnergySpecCalc+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mona.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mona.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mona.cc	(revision 3781)
@@ -0,0 +1,340 @@
+#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");
+    }
+}
+
+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);
+
+    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]", "MPedestalCam", "FillPedestal");
+    MFillH hfilld("PedestalRms", "MPedestalCam", "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("Mars", &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.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-8-4/MagicSoft/Mars/mpointing/MPointingPos.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPos.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPos.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mpointing/MPointingPos.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPos.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPos.h	(revision 3781)
@@ -0,0 +1,50 @@
+#ifndef MARS_MPointingPos
+#define MARS_MPointingPos
+
+#ifndef MARS_MParContainer
+#include "MParContainer.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)
+    {
+        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 GetRa() const  { return fRa; }
+    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-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.cc	(revision 3781)
@@ -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, 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()
+{
+    switch (fRunType)
+    {
+    case MRawRunHeader::kRTData:
+        fPosition->SetLocalPosition(fReport->GetNominalZd(), fReport->GetNominalAz());
+        fPosition->SetSkyPosition(fReport->GetRa()*TMath::DegToRad()/15, fReport->GetDec()*TMath::DegToRad());
+        return kTRUE;
+
+    case MRawRunHeader::kRTMonteCarlo:
+        fPosition->SetLocalPosition(fMcEvt->GetTelescopeTheta()*TMath::RadToDeg(), fMcEvt->GetTelescopePhi()*TMath::RadToDeg());
+        return kTRUE;
+    }
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MPointingPosCalc.h	(revision 3781)
@@ -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()
+    {
+        fName  = "MPointingPosCalc";
+        fTitle = "Task calculating the pointing position";
+    }
+
+    ClassDef(MPointingPosCalc, 0) //Task calculating the pointing position
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.cc	(revision 3781)
@@ -0,0 +1,192 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// MSrcPosCalc
+//
+// Calculate the current source position in the camera from the (already
+// corrected) local pointing position of the telescope (MPointingPos) by
+// derotating the position (given in x and y coordinates in the camera
+// plane) at culmination time by the current rotation angle of the
+// starfield dtermined from MObservatory and MPointingPos
+//
+// The conversion factor between the camera plain (mm) and the
+// sky (deg) is taken from MGeomCam.
+//
+// Input Container:
+//   MPointingPos
+//   MObservatory
+//   MGeomCam
+//
+// Output Container:
+//   MSrcPosCam
+//
+// To be done:
+//   - wobble mode missing
+//   - a switch between using sky-coordinates and time or local-coordinates
+//     from MPointingPos for determin the rotation angle
+//   - the center of rotation need not to be the camera center
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MSrcPosCalc.h"
+
+#include "MParList.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawRunHeader.h"
+#include "MObservatory.h"
+#include "MSrcPosCam.h"
+#include "MAstroSky2Local.h"
+#include "MPointingPos.h"
+#include "MGeomCam.h"
+
+ClassImp(MSrcPosCalc);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Initialize fY and fY with 0
+//
+MSrcPosCalc::MSrcPosCalc(const char *name, const char *title)
+    : fX(0), fY(0)
+{
+    fName  = name  ? name  : "MSrcPosCalc";
+    fTitle = title ? title : "Derotates the source position in the camera";
+}
+
+// --------------------------------------------------------------------------
+//
+// Search and if necessary create MSrcPosCam in the parameter list
+//
+Int_t MSrcPosCalc::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;
+    }
+
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// Search the parameter list for MObservatory and MTime
+//
+Bool_t MSrcPosCalc::ReInit(MParList *pList)
+{
+    if (fX!=0 || fY!=0)
+        return kTRUE;
+
+    *fLog << warn << "fX==0 && fY==0: Using arbitrary source position!" << endl;
+
+    //
+    // This is a workaround for current crab misspointing - DO NOT USE!
+    // It will be removed soon!
+    //
+    const MRawRunHeader *h = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!h)
+    {
+        *fLog << err << "MRawRunHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    const MTime &t = h->GetRunStart();
+
+    const Double_t rho = fPointPos->RotationAngle(*fObservatory, t);
+
+    // Calculate x, y of Zeta Tauri
+
+    Double_t tm = t.GetAxisTime();
+
+    Double_t x = 1.7267e6-6.03285e-3*tm; // [mm]
+    Double_t y = -189.823+974.908*exp(-52.3083*(tm*1e-5-2861.5)); // [mm]
+
+    const Double_t cs = TMath::Cos(rho-fDrho);
+    const Double_t sn = TMath::Sin(rho-fDrho);
+
+    const Double_t dx = fR*cs;
+    const Double_t dy = fR*sn;
+
+    fSrcPos->SetXY(x-dx, y-dy);
+
+    *fLog << dbg << t << " - Position: x=" << x-dx << "mm y=" << y-dy << "mm" << endl;
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// Derotate fX/fY by the current rotation angle, set MSrcPosCam
+//
+Int_t MSrcPosCalc::Process()
+{
+    if (fX==0 && fY==0)
+        return kTRUE;
+
+    // rotate the source position by the current rotation angle
+    const Double_t rho = fPointPos->RotationAngle(*fObservatory, *fTime);
+
+    // Define source position in the camera plain
+    TVector2 v(fX, fY);
+    v=v.Rotate(rho);
+
+    // Convert coordinates into camera plain (mm)
+    v *= 1./fGeom->GetConvMm2Deg();
+
+    // Set current source position
+    fSrcPos->SetXY(v);
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCalc.h	(revision 3781)
@@ -0,0 +1,47 @@
+#ifndef MARS_MSrcPosCalc
+#define MARS_MSrcPosCalc
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MObservatory;
+class MPointingPos;
+class MSrcPosCam;
+class MGeomCam;
+class MTime;
+
+class MSrcPosCalc : public MTask
+{
+private:
+    MObservatory *fObservatory;
+    MPointingPos *fPointPos;
+    MSrcPosCam   *fSrcPos;
+    MGeomCam     *fGeom;
+    MTime        *fTime;
+
+    Double_t fR;    // Distance of source to a fitted star
+    Double_t fDrho; // angle between the two stars
+
+    Double_t fX;    // [deg] x-position of source
+    Double_t fY;    // [deg] y-position of source
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Bool_t ReInit(MParList *pList);
+
+public:
+    MSrcPosCalc(const char *name=NULL, const char *title=NULL);
+
+    // Use is deprecated!
+    void SetOffset(Double_t r, Double_t drho)
+    {
+        fDrho = drho*TMath::DegToRad();
+        fR    = r;
+    }
+    void SetPositionXY(Double_t x, Double_t y) { fX=x; fY=y; }
+
+    ClassDef(MSrcPosCalc, 0) // Derotates the source position in the camera
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/MSrcPosCam.h	(revision 3781)
@@ -0,0 +1,40 @@
+#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
+
+    void StreamPrimitive(ofstream &out) const;
+
+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 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-8-4/MagicSoft/Mars/mpointing/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/Makefile	(revision 3781)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT = Pointing
+
+#
+# Library name to creatre
+#
+LIB  = mpointing.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../mreport -I../mmc \
+           -I../mastro -I../mgeom
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MPointingPos.cc \
+	   MPointingPosCalc.cc \
+           MSrcPosCam.cc \
+           MSrcPosCalc.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingIncl.h	(revision 3781)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <TVector2.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mpointing/PointingLinkDef.h	(revision 3781)
@@ -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 MPointingPos+;
+#pragma link C++ class MPointingPosCalc+;
+
+#pragma link C++ class MSrcPosCalc+;
+#pragma link C++ class MSrcPosCam+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForest.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForest.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForest.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MHRanForest.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForest.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForest.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MHRanForestGini.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanForest.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForest.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForest.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanForest.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForest.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForest.h	(revision 3781)
@@ -0,0 +1,102 @@
+#ifndef MARS_MRanForest
+#define MARS_MRanForest
+
+#ifndef MARS_MParContainer
+#include "MParContainer.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; }
+    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, 0) // Storage container for tree structure
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.cc	(revision 3781)
@@ -0,0 +1,254 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both 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 "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)
+{
+    //
+    //   set the name and title of this object
+    //
+    fName  = name  ? name  : gsDefName.Data();
+    fTitle = title ? title : gsDefTitle.Data();
+}
+
+// --------------------------------------------------------------------------
+//
+// Delete the data chains
+//
+MRanForestCalc::~MRanForestCalc()
+{
+    //    delete fData;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    fRanForest = (MRanForest*)plist->FindObject("MRanForest");
+    if (!fRanForest)
+    {
+        *fLog << err << dbginf << "MRanForest not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRanTree = (MRanTree*)plist->FindObject("MRanTree");
+    if (!fRanTree)
+    {
+        *fLog << err << dbginf << "MRanTree not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    /*if(!fRanForest->GetCurTree())
+    {
+        *fLog << err << dbginf << "MRanForest does not contain trees... 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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestCalc.h	(revision 3781)
@@ -0,0 +1,53 @@
+#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();
+
+public:
+    MRanForestCalc(const char *name=NULL, const char *title=NULL);
+    ~MRanForestCalc();
+
+    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-8-4/MagicSoft/Mars/mranforest/MRanForestFill.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestFill.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestFill.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanForestFill.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestFill.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestFill.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanForestGrow.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/MRanTree.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanTree.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanTree.cc	(revision 3781)
@@ -0,0 +1,522 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both 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)
+{
+    return TreeHad(TMatrixRow(m, ievt));
+}
+
+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-8-4/MagicSoft/Mars/mranforest/MRanTree.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanTree.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/MRanTree.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mranforest/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/Makefile	(revision 3781)
@@ -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  = RanForest
+
+#
+# Library name to creatre
+#
+LIB   = mranforest.a
+
+#
+#  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
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MRanTree.cc \
+           MRanForest.cc \
+           MRanForestGrow.cc \
+           MRanForestCalc.cc \
+           MRanForestFill.cc \
+	   MHRanForest.cc \
+	   MHRanForestGini.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mranforest/RanForestLinkDef.h	(revision 3781)
@@ -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 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+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateArray.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateArray.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateArray.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mraw/MRawCrateArray.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateArray.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateArray.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mraw/MRawCrateData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateData.cc	(revision 3781)
@@ -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 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);
+}
+
+// --------------------------------------------------------------------------
+//
+//  print all stored information to gLog
+//
+void MRawCrateData::Print(Option_t *t) const
+{
+    *fLog << all;
+    *fLog << "Crate Number " << dec << fDAQCrateNumber << ":  ";
+    *fLog << "FADCEventNr   = " << fFADCEvtNumber << "  ";
+    *fLog << "FADCClockTick = " << fFADCClockTick << " (20MHz)" << endl;
+    *fLog << "ABFlags       = " << hex << fABFlags << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawCrateData.h	(revision 3781)
@@ -0,0 +1,35 @@
+#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);
+
+    ClassDef(MRawCrateData, 2) //Container to store the Raw CRATE DATA
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.cc	(revision 3781)
@@ -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): 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 3:
+//   ----------
+//    - 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)
+{
+    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
+//
+Byte_t MRawEvtData::GetNumHiGainSamples() const
+{
+    return fHiGainPixId->GetSize() ? fHiGainFadcSamples->GetSize()/fHiGainPixId->GetSize() : 0;
+}
+
+// --------------------------------------------------------------------------
+//
+// return the number of lo gain samples per pixel
+//
+Byte_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 Byte_t nHiSamp = GetNumHiGainSamples();
+    const Byte_t nLoSamp = GetNumLoGainSamples();
+
+    const UShort_t nHiPix = fHiGainPixId->GetSize();;
+    const UShort_t nLoPix = fLoGainPixId->GetSize();;
+
+    fLog->unsetf(ios::showbase);
+
+    *fLog << dec << all;
+    *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 << " <" << 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 arrays describing the pixel Id and Samples in pixels.
+// The flag is for future usage.
+//
+void MRawEvtData::DeletePixels(Bool_t flag)
+{
+    if (fRunHeader && flag)
+    {
+        //const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();
+        const int npix = fRunHeader->GetNumConnectedPixels();
+
+        if (fArraySize == npix)
+        {
+            fPosInArray = 0;
+            fConnectedPixels = 0;
+            return;
+        }
+    }
+
+    DeleteArrays();
+    InitArrays(flag);
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//
+void MRawEvtData::DeleteArrays()
+{
+    delete fHiGainPixId;
+    delete fLoGainPixId;
+    delete fHiGainFadcSamples;
+    delete fLoGainFadcSamples;
+    delete fABFlags;
+}
+
+// --------------------------------------------------------------------------
+//
+//  Deletes all the arrays
+//  The flag is for future usage.
+//
+void MRawEvtData::InitArrays(Bool_t flag)
+{
+    if (flag && fRunHeader)
+    {
+        //const int npix = fRunHeader->GetNumCrates()*fRunHeader->GetNumPixInCrate();
+        const int npix = fRunHeader->GetNumConnectedPixels();
+
+        fHiGainPixId       = new MArrayS(npix);
+        fLoGainPixId       = new MArrayS(npix);
+        fHiGainFadcSamples = new MArrayB(npix*fRunHeader->GetNumSamplesHiGain());
+        fLoGainFadcSamples = new MArrayB(npix*fRunHeader->GetNumSamplesLoGain());
+        fABFlags           = new TArrayC(fRunHeader->GetMaxPixId());
+
+        fArraySize  = npix;
+    }
+    else
+    {
+        fHiGainPixId       = new MArrayS(0);
+        fLoGainPixId       = new MArrayS(0);
+        fHiGainFadcSamples = new MArrayB(0);
+        fLoGainFadcSamples = new MArrayB(0);
+        fABFlags           = new TArrayC(0);
+
+        fArraySize = 0;
+    }
+
+    fPosInArray = 0;
+    fConnectedPixels = 0;
+}
+
+// --------------------------------------------------------------------------
+//
+//  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 Byte_t ns    = data->GetSize();
+    const Byte_t nSamp = lflag ? GetNumLoGainSamples() : GetNumHiGainSamples();
+    if (nSamp && ns!=nSamp)
+    {
+        *fLog << err << "RawEvtData::AddPixel: Error, number of samples in ";
+        *fLog << "TArrayC doesn't match actual number" << 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);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    const UShort_t nlo = fRunHeader->GetNumSamplesLoGain();
+    const UShort_t nhi = fRunHeader->GetNumSamplesHiGain();
+
+    const UShort_t npic = fRunHeader->GetNumPixInCrate();
+
+    const UShort_t npos = npic*fPosInArray;
+
+    const Byte_t ab = fCrateArray->GetEntry(fPosInArray)->GetABFlags();
+
+    Byte_t *higainsam = fHiGainFadcSamples->GetArray()+nhi*fConnectedPixels;
+    Byte_t *logainsam = fLoGainFadcSamples->GetArray()+nlo*fConnectedPixels;
+
+    for (int i=0; i<npic; i++)
+    {
+        fin.read((char*)higainsam, nhi);
+        fin.read((char*)logainsam, nlo);
+
+        // calc the spiral hardware pixel number
+        const UShort_t ipos = npos+i;
+
+        // -1 converts the hardware pixel Id into the software pixel index
+        const Int_t npix = (Int_t)fRunHeader->GetPixAssignment(ipos)-1;
+
+        // Check whether the pixel is connected or not
+        if (npix<0)
+            continue;
+
+        //
+        //  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
+        //
+        fHiGainPixId->AddAt(npix, fConnectedPixels);
+        higainsam += nhi;
+
+        // FIXME: Not implemented in the raw files yet
+        //if (IsLoGainOn(i, j))
+        //{
+        fLoGainPixId->AddAt(npix, fConnectedPixels);
+        logainsam += nlo;
+        //}
+
+        if (TESTBIT(ab, i))
+            SETBIT((*fABFlags)[npix/8], npix%8);
+        else
+            CLRBIT((*fABFlags)[npix/8], npix%8);
+
+        fConnectedPixels++;
+    }
+
+    fPosInArray++;
+}
+
+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.fPosInArray      = fPosInArray;
+    evt.fConnectedPixels = fConnectedPixels;
+    evt.fArraySize       = fArraySize;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtData.h	(revision 3781)
@@ -0,0 +1,91 @@
+#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
+    MRawCrateArray *fCrateArray;  //! provides information about ab flag
+
+    // 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)
+
+    TArrayC *fABFlags;            //-> A information about the exact trigger position
+
+    Int_t fPosInArray;        //!
+    Int_t fConnectedPixels;   //!
+    Int_t fArraySize;         //!
+
+    void InitArrays(Bool_t flag=kFALSE);
+    void DeleteArrays();
+
+public:
+    MRawEvtData(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtData();
+
+    void Init(MRawRunHeader *rh, MRawCrateArray *arr)
+    {
+        //
+        // you have to set this before you can read information
+        // from a magic binary file
+        //
+        fRunHeader  = rh;
+        fCrateArray = arr;
+    }
+
+    void Clear(Option_t * = NULL);
+    void Print(Option_t * = NULL) const;
+    void Draw (Option_t * = NULL);
+
+    void DeletePixels(Bool_t flag=kFALSE);
+    void ResetPixels() { DeletePixels(kTRUE); }
+    void AddPixel(UShort_t nOfPixel, TArrayC *data, Bool_t lflag=kFALSE);
+
+    Byte_t   GetNumHiGainSamples() const;
+    Byte_t   GetNumLoGainSamples() const;
+    UShort_t GetNumPixels() const;
+
+    void ReadEvt(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, 4) //Container to store the raw Event Data
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.cc	(revision 3781)
@@ -0,0 +1,363 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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[2]
+// -----------------------
+// 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).
+//
+// 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) 
+//
+/////////////////////////////////////////////////////////////////////////////
+#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::Init(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;
+    }
+    *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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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]) 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) 
+    // ----------
+    //
+    // 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.
+    //
+    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)
+    //
+    return fTime->UpdMagicTime(h, m, s, ns);
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MRawEvtHeader::ReadEvt(istream &fin, UShort_t ver)
+{
+    fin.read((char*)&fDAQEvtNumber, 4);  // Total=4
+
+    UInt_t abstime[2];
+    fin.read((char*)abstime,        8);  // Total=12
+
+    if (ver>2)
+        if (!DecodeTime(abstime))
+        {
+            *fLog << err << "ERROR - Event time in event header invalid... abort." << endl;
+            return kFALSE;
+        }
+
+    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();
+}
+
+// --------------------------------------------------------------------------
+//
+//   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
+{
+  UInt_t trigID=0;
+
+  trigID = fTrigPattern[0];
+
+  return trigID;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtHeader.h	(revision 3781)
@@ -0,0 +1,72 @@
+#ifndef MARS_MRawEvtHeader
+#define MARS_MRawEvtHeader
+
+#ifndef MARS_MParContainer
+#include "MParContainer.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
+    };
+
+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]) const;
+
+public:
+    MRawEvtHeader(const char *name=NULL, const char *title=NULL);
+    ~MRawEvtHeader();
+
+    void Init(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;
+
+    int ReadEvt(istream& fin, UShort_t ver);
+
+    ClassDef(MRawEvtHeader, 1) // Parameter Conatiner for raw EVENT HEADER
+}; 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.cc	(revision 3781)
@@ -0,0 +1,349 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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) : fData(dat)
+{
+    fNumHiGainSamples = dat->GetNumHiGainSamples();
+    fNumLoGainSamples = dat->GetNumLoGainSamples();
+
+    Reset();
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 (fNumLoGainEntry != fData->fLoGainPixId->GetSize())
+        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->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 = ptr + 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 = ptr + 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 = ptr + 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 = ptr + 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 *max = fLoGainPos+lofirst;
+  Byte_t *ptr = max+1;
+
+  const Byte_t *end = fLoGainPos + fNumLoGainSamples + 1;
+  
+  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 = ptr + 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 = ptr + fNumLoGainSamples;
+
+    ULong_t sum=0;
+
+    do sum += (*ptr)*(*ptr);
+    while (++ptr != end);
+
+    return sum;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawEvtPixelIter.h	(revision 3781)
@@ -0,0 +1,133 @@
+#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
+
+    Char_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
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return fLoGainId && *fHiGainId==*fLoGainId;
+    }
+    Bool_t HasABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return TESTBIT(fABFlags[GetPixelId()/8], GetPixelId()%8);
+    }
+    Byte_t GetABFlag() const
+    {
+        //
+        // return kTRUE  the lo gains exist for the actual pixel, else return kFALSE
+        //
+        return (Byte_t)fABFlags[GetPixelId()/8];
+    }
+
+    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-8-4/MagicSoft/Mars/mraw/MRawFileRead.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileRead.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileRead.cc	(revision 3781)
@@ -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@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.          //
+//                                                                          //
+//  Input Containers:                                                       //
+//   -/-                                                                    //
+//                                                                          //
+//  Output Containers:                                                      //
+//   MRawRunHeader, MRawEvtHeader, MRawEvtData, MRawCrateArray, MRawEvtTime //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+#include "MRawFileRead.h"
+
+#include <errno.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(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)
+    : fFileName(fname), fIn(NULL)
+{
+    fName  = name  ? name  : "MRawFileRead";
+    fTitle = title ? title : "Read task to read DAQ binary files";
+
+    fIn = new ifstream;
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor. Delete input stream.
+//
+MRawFileRead::~MRawFileRead()
+{
+    delete fIn;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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)
+{
+    //
+    // 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 (!MRawRead::PreProcess(pList))
+        return kFALSE;
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    if (!fRawRunHeader->ReadEvt(*fIn))
+        return kFALSE;
+
+    if (!(*fIn))
+    {
+        *fLog << err << "Error: Accessing file '" << fFileName << "'" << endl;
+        return kFALSE;
+    }
+    //if (fRawRunHeader->GetMagicNumber()!=kMagicNumber)
+    //    return kFALSE;
+
+    fRawRunHeader->Print();
+
+    *fRawEvtTime = fRawRunHeader->GetRunStart();
+
+    //
+    // Give the run header information to the 'sub-classes'
+    // Run header must be valid!
+    //
+    fRawEvtHeader->Init(fRawRunHeader, fRawEvtTime);
+    fRawEvtData  ->Init(fRawRunHeader, fRawCrateArray);
+
+    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()
+{
+    return ReadEvent(*fIn);
+}
+
+// --------------------------------------------------------------------------
+//
+//  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()
+{
+    fIn->close();
+
+    //
+    // Sanity check for the number of events
+    //
+    if (fRawRunHeader->GetNumEvents()==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 (";
+    *fLog << fRawRunHeader->GetNumEvents() << ")." << endl;
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileRead.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileRead.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileRead.h	(revision 3781)
@@ -0,0 +1,27 @@
+#ifndef MARS_MRawFileRead
+#define MARS_MRawFileRead
+
+#ifndef MARS_MRawRead
+#include "MRawRead.h"
+#endif
+
+class MRawFileRead : public MRawRead
+{
+private:
+    TString   fFileName;
+    ifstream *fIn;        //! buffered input stream (file to read from)
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+public:
+    MRawFileRead(const char *filename, const char *name=NULL, const char *title=NULL);
+    ~MRawFileRead();
+
+    const TString &GetFileName() const { return fFileName; }
+
+    ClassDef(MRawFileRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileWrite.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileWrite.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileWrite.cc	(revision 3781)
@@ -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): 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, MRawCrateArray, MRawEvtTime
+//
+//  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)
+{
+    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()
+{
+    //
+    // 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;
+    }
+
+    //
+    // remember the pointer to the parameter list fur further usage
+    //
+    pParList = pList;
+
+    //
+    //  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 << dbginf << "MRawEvtHeader not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawEvtData = (MRawEvtData*)pList->FindObject("MRawEvtData");
+    if (!fRawEvtData)
+    {
+        *fLog << err << dbginf << "MRawEvtData not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawCrateArray = (MRawCrateArray*)pList->FindObject("MRawCrateArray");
+    if (!fRawCrateArray)
+    {
+        *fLog << err << dbginf << "MRawCrateArray not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fTime = (MTime*)pList->FindObject("MTime");
+    if (!fTime)
+    {
+        *fLog << err << dbginf << "MTime not found... aborting." << endl;
+        return kFALSE;
+    }
+
+    fRawRunHeader = (MRawRunHeader*)pList->FindObject("MRawRunHeader");
+    if (!fRawRunHeader)
+    {
+        *fLog << err << dbginf << "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
+    //
+
+    //
+    // Write the run header information to the file
+    //
+    TTree *rh = new TTree("RunHeaders", "Run headers of all runs in this file");
+    rh->Branch("MRawRunHeader.", "MRawRunHeader", &fRawRunHeader, 32000);
+    rh->Fill();
+    //rh->Write();
+
+    //
+    // create data trees for the three types of data
+    //
+    fTData        = new TTree("Events",      "Normal Triggered Events");
+    fTPedestal    = new TTree("Pedestals",   "Pedestal Triggered Events");
+    fTCalibration = new TTree("Calibration", "Calibration Triggered Events");
+
+    //
+    // 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);
+    fTPedestal   ->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTCalibration->Branch("MTime.",          "MTime",          &fTime,          32000);
+    fTData       ->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTPedestal   ->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTCalibration->Branch("MRawEvtHeader.",  "MRawEvtHeader",  &fRawEvtHeader,  32000);
+    fTData       ->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData,    320000);
+    fTPedestal   ->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData,    320000);
+    fTCalibration->Branch("MRawEvtData.",    "MRawEvtData",    &fRawEvtData,    320000);
+    //fTree->Branch("MRawCrateArray",  fRawCrateArray->GetArray(),      32000, 1);
+    fTData       ->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    fTPedestal   ->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+    fTCalibration->Branch("MRawCrateArray.", "MRawCrateArray", &fRawCrateArray, 32000);
+
+    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-8-4/MagicSoft/Mars/mraw/MRawFileWrite.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileWrite.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawFileWrite.h	(revision 3781)
@@ -0,0 +1,49 @@
+#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:
+    MParList *pParList;
+
+    MTime          *fTime;
+    MRawRunHeader  *fRawRunHeader;
+    MRawEvtHeader  *fRawEvtHeader;
+    MRawEvtData    *fRawEvtData;
+    MRawCrateArray *fRawCrateArray;
+
+    TTree *fTData;                  //!
+    TTree *fTPedestal;              //!
+    TTree *fTCalibration;           //!
+
+    TFile *fOut;                    //!
+
+public:
+    MRawFileWrite(const char *fname,
+                  const Option_t *opt="RECREATE",
+                  const char *ftitle="Untitled",
+                  const Int_t comp=1,
+                  const char *name=NULL, const char *title=NULL);
+    ~MRawFileWrite();
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+
+    ClassDef(MRawFileWrite, 0)	// Task to write the raw data containers to a root file
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.cc	(revision 3781)
@@ -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 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
+//   MRawCrateArray
+//   MRawEvtTime
+//                                                                          
+//////////////////////////////////////////////////////////////////////////////
+#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)
+{
+    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;
+
+    fRawEvtData = (MRawEvtData*)pList->FindCreateObj("MRawEvtData");
+    if (!fRawEvtData)
+        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
+    //
+    if (!fRawEvtHeader->ReadEvt(fin, ver))
+        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)
+    //
+    fRawEvtData->ResetPixels();
+
+    //
+    // clear the TClonesArray which stores the Crate Information
+    // and create a new array of the correct size
+    //
+    fRawCrateArray->SetSize(nc);
+
+    //
+    // read the CRATE DATA (see specification) from file
+    //
+    for (int i=0; i<nc; i++)
+    {
+        fRawCrateArray->GetEntry(i)->ReadEvt(fin, ver);
+        if (!fin)
+            return kFALSE;
+
+        fRawEvtData->ReadEvt(fin);
+        if (!fin)
+            return kFALSE;
+    }
+
+    // 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();
+
+    // FIXME: For all other runs we should enhance the precision
+    //        of the time-stamp by using the FADCClockTick
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRead.h	(revision 3781)
@@ -0,0 +1,38 @@
+#ifndef MARS_MRawRead
+#define MARS_MRawRead
+
+#ifndef MARS_MTask
+#include "MTask.h"
+#endif
+
+class MTime;
+class MParList;
+class MRawRunHeader;
+class MRawEvtHeader;
+class MRawEvtData;
+class MRawCrateArray;
+
+class MRawRead : public MTask
+{
+protected:
+    MRawRunHeader  *fRawRunHeader;  // run header information container to fill from file
+    MRawEvtHeader  *fRawEvtHeader;  // event header information container to fill from file
+    MRawEvtData    *fRawEvtData;    // raw evt header infomation container to fill from file
+    MRawCrateArray *fRawCrateArray; // crate information array container to fill from file
+    MTime          *fRawEvtTime;    // raw evt time information container to fill from file
+
+    void CreateFakeTime() const;
+
+    Bool_t ReadEvent(istream &fin);
+    Int_t  PreProcess(MParList *pList);
+
+private:
+    virtual Bool_t OpenStream() { return kTRUE; }
+
+public:
+    MRawRead(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MRawRead, 0)	// Task to read the raw data binary file
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRunHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRunHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRunHeader.cc	(revision 3781)
@@ -0,0 +1,312 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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
+//
+//  Format Version 2:
+//  -----------------
+//   - removed mjd from data
+//   - added start time
+//   - added stop  time
+//
+//  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 =      3;
+
+// --------------------------------------------------------------------------
+//
+// 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 << "WARNING - 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
+//
+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 << "Samples:      " << fNumSamplesLoGain << "/" << fNumSamplesHiGain << " (lo/hi) = " << (fNumSamplesLoGain+fNumSamplesHiGain) * fNumCrates * fNumPixInCrate /1024 << "kB/Evt" << endl;
+    *fLog << "Evt Counter:  " << fNumEvents << endl;
+
+    *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
+//
+UShort_t MRawRunHeader::GetPixAssignment(UShort_t i) const
+{
+    // FIXME: Do we need a range check here?
+    return (*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 maximum id which exists in the pix assignment
+//
+UShort_t MRawRunHeader::GetMaxPixId() const
+{
+    const Int_t num = fPixAssignment->GetSize();
+
+    UShort_t rc = 0;
+    for (int i=0; i<num; i++)
+        rc = TMath::Max(GetPixAssignment(i), rc);
+
+    return 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-8-4/MagicSoft/Mars/mraw/MRawRunHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRunHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawRunHeader.h	(revision 3781)
@@ -0,0 +1,117 @@
+#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; }
+    UShort_t GetPixAssignment(UShort_t i) const;
+    UShort_t GetMaxPixId() const;
+    UShort_t GetNumConnectedPixels() 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-8-4/MagicSoft/Mars/mraw/MRawSocketRead.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawSocketRead.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawSocketRead.cc	(revision 3781)
@@ -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 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 "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()
+{
+    /*
+    sprintf(report_str, " %8.8d %8.8d %6.6d",
+    run_header->RunNumber, run.event_number,
+    time.tv_sec - run.time_start_secs);
+    if (send(sd, report_str, strlen(report_str), flags) == -1) {
+    return -1;
+    }
+
+    sprintf(report_str, " %6.1f %6.1f %6.6d %7.4f %8.8d %6.6d ",
+    trigrate_hz, storerate_hz, storerate_kbps, gammarate_hz,
+    diskspace_kb, remtime_sec);
+    if (send(sd, report_str, strlen(report_str), flags) == -1) {
+    return -1;
+    }
+    */
+    char dummy[126];
+    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;
+    }
+
+    char size[6] = {0,0,0,0,0,0};
+    fIn->read(size, 5);
+    fIn->read(dummy, 126); //00000[CC-DATA]\n
+
+    /*
+    int numevt;
+    sscanf(dummy,  "%*s %*d %*d %*d %*d %*d %*d %*d "
+           "%*d %*d %*d %*d %*d %*d %*d %*d %*d %*d "
+           "%d %*d %*f %*f %*d %*f %*d %*d", &numevt);
+    */
+
+    //
+    // Read RUN HEADER (see specification) from input stream
+    //
+    fLog->SetNullOutput();
+    const Bool_t rc = fRawRunHeader->ReadEvt(*fIn);
+    fLog->SetNullOutput(kFALSE);
+
+    if (!rc)
+        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(size)==fRawRunHeader->GetNumTotalBytes())
+    {
+        *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->Init(fRawRunHeader, fRawEvtTime);
+    fRawEvtData  ->Init(fRawRunHeader, fRawCrateArray);
+
+    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-8-4/MagicSoft/Mars/mraw/MRawSocketRead.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawSocketRead.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/MRawSocketRead.h	(revision 3781)
@@ -0,0 +1,36 @@
+#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; }
+
+    ClassDef(MRawSocketRead, 0)	//Task to read DAQ binary data from tcp/ip socket
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/Makefile	(revision 3781)
@@ -0,0 +1,57 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Raw
+
+#
+# Library name to creatre
+#
+LIB   = mraw.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom -I../MBase
+# mgui (MCamEvent), mgeom(MGeomCam)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MRawRunHeader.cc \
+	   MRawEvtHeader.cc \
+	   MRawEvtData.cc \
+	   MRawEvtPixelIter.cc \
+	   MRawCrateArray.cc \
+	   MRawCrateData.cc \
+           MRawRead.cc \
+           MRawFileWrite.cc \
+           MRawFileRead.cc \
+           MRawSocketRead.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawIncl.h	(revision 3781)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mraw/RawLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflEvtData.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtData.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtData.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflEvtData.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtData.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtData.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflEvtHeader.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflRunHeader.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/MRflSinglePhoton.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreflector/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/Makefile	(revision 3781)
@@ -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  = Reflector
+
+#
+# Library name to creatre
+#
+LIB   = mreflector.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mgui -I../mgeom
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MRflEvtData.cc \
+	   MRflEvtHeader.cc \
+	   MRflRunHeader.cc \
+	   MRflSinglePhoton.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreflector/ReflectorLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mreport/MReport.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReport.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReport.cc	(revision 3781)
@@ -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)
+{
+    *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)
+{
+    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);
+    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-8-4/MagicSoft/Mars/mreport/MReport.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReport.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReport.h	(revision 3781)
@@ -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  Interprete(TString &str, const MTime &start, const MTime &stop);
+    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-8-4/MagicSoft/Mars/mreport/MReportCC.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCC.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCC.cc	(revision 3781)
@@ -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)
+{
+    // 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-8-4/MagicSoft/Mars/mreport/MReportCC.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCC.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCC.h	(revision 3781)
@@ -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);
+
+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-8-4/MagicSoft/Mars/mreport/MReportCamera.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCamera.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCamera.cc	(revision 3781)
@@ -0,0 +1,458 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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 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)
+{
+    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 (str!="OVER")
+    {
+        *fLog << warn << "WARNING - 'OVER' tag not found." << endl;
+        return kCONTINUE;
+    }
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCamera.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCamera.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCamera.h	(revision 3781)
@@ -0,0 +1,52 @@
+#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);
+
+    Int_t  InterpreteBody(TString &str);
+
+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-8-4/MagicSoft/Mars/mreport/MReportCurrents.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCurrents.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCurrents.cc	(revision 3781)
@@ -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 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-8-4/MagicSoft/Mars/mreport/MReportCurrents.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCurrents.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportCurrents.h	(revision 3781)
@@ -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);
+
+public:
+    MReportCurrents();
+
+    ClassDef(MReportCurrents, 1) // Class for DC-REPORT information
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.cc	(revision 3781)
@@ -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)
+{
+    *fLog << dbg << "D" << flush;
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDAQ.h	(revision 3781)
@@ -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);
+
+public:
+    MReportDAQ();
+
+    ClassDef(MReportDAQ, 1) // Class for DAQ-REPORT information
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.cc	(revision 3781)
@@ -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, 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")
+{
+    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)
+{
+    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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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();
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportDrive.h	(revision 3781)
@@ -0,0 +1,49 @@
+#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;    // [?] system error in the zenith angle axis
+    Double_t fErrorAz;    // [?] sistem error in the azimuth angle axis
+
+    Int_t InterpreteBody(TString &str);
+
+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;
+
+    ClassDef(MReportDrive, 1) // Class for DRIVE-REPORT information
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportFileRead.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportFileRead.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportFileRead.cc	(revision 3781)
@@ -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): 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;
+
+const TString MReportFileRead::gsReportHeader ="[CC Report File]";
+const TString MReportFileRead::gsVersionPrefix="Arehucas Version Number";
+
+// --------------------------------------------------------------------------
+//
+// 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), fIn(NULL)
+{
+    fName  = name  ? name  : "MReportFileRead";
+    fTitle = title ? title : "Read task to read Central Control 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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 MReportFileRead::CheckFileHeader() const
+{
+    Int_t line = 0;
+
+    TString str;
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (str != gsReportHeader)
+    {
+        *fLog << err << "ERROR - First line doesn't match '" << gsReportHeader <<"' ";
+        *fLog << "in file '" << fFileName << "'"<<endl;
+        return line;
+    }
+    line++;
+
+    str.ReadLine(*fIn);   // Read to EOF or newline
+    if (!str.BeginsWith(gsVersionPrefix))
+    {
+        *fLog << err << "ERROR - Version prefix '" << gsVersionPrefix <<"' ";
+        *fLog << "not found in second line of file '" << fFileName << "'"<<endl;
+        return line;
+    }
+    line++;
+
+    str.Remove(0, gsVersionPrefix.Length());
+    str = str.Strip(TString::kBoth);
+
+    TString ver = str(TRegexp("^[0-9][0-9][0-9][0-9][0-9][0-9]-[0-9]$"));
+    if (ver.IsNull())
+    {
+        *fLog << err << "ERROR - Version string '" << str <<"' doesn't ";
+        *fLog << "match regular expression." << endl;
+        return line;
+    }
+
+    *fLog << dbg << "Report File version: <" << ver << ">" << endl;
+
+    return line;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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);
+
+    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-8-4/MagicSoft/Mars/mreport/MReportFileRead.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportFileRead.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportFileRead.h	(revision 3781)
@@ -0,0 +1,62 @@
+#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:
+    static const TString gsReportHeader;
+    static const TString gsVersionPrefix;
+
+    TString     fFileName;
+    ifstream   *fIn;         //! buffered input stream (file to read from)
+
+    THashTable *fList;
+
+    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
+
+    enum { kHasNoHeader = BIT(14) };
+
+    Int_t PreProcess(MParList *pList);
+    Int_t Process();
+    Int_t PostProcess();
+
+    Int_t CheckFileHeader() const;
+    MReport *GetReport(const TString &str) const;
+    MReport *GetReport(MReportHelp *help) const;
+    MReportHelp *GetReportHelp(const TString &str) const;
+
+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 the central control report file
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportHelp.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportHelp.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportHelp.cc	(revision 3781)
@@ -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)
+{
+    const Int_t rc = fReport->Interprete(str, start, stop);
+
+    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-8-4/MagicSoft/Mars/mreport/MReportHelp.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportHelp.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportHelp.h	(revision 3781)
@@ -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);
+
+    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-8-4/MagicSoft/Mars/mreport/MReportRun.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportRun.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportRun.cc	(revision 3781)
@@ -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/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(0)
+{
+    fName  = "MReportRun";
+    fTitle = "Class for RUN-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the RUN-REPORT string
+//
+Int_t MReportRun::InterpreteBody(TString &str)
+{
+    Int_t len;
+    const Int_t n=sscanf(str.Data(), "%d %n", &fRunNumber, &len);
+    if (n!=1)
+    {
+        *fLog << warn << "WARNING - Wrong number of arguments." << endl;
+        return kCONTINUE;
+    }
+    str.Remove(0, len);
+
+    if (str.BeginsWith("END"))
+        fRunNumber = -1;
+
+    str.Remove(0, 6);
+    str = str.Strip(TString::kBoth);
+    Ssiz_t pos = str.First(' ');
+    if (pos<0)
+        pos = str.Length();
+    fSourceName = str(0, pos+1);
+
+    return kTRUE;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportRun.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportRun.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportRun.h	(revision 3781)
@@ -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);
+
+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-8-4/MagicSoft/Mars/mreport/MReportTrigger.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportTrigger.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportTrigger.cc	(revision 3781)
@@ -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, 11/2003 <mailto:tbretz@astro.uni-wuerzburg.de>
+!
+!   Copyright: MAGIC Software Development, 2000-2003
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//  MReportTrigger
+//
+// This is the class interpreting and storing the TRIGGER-REPORT information.
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MReportTrigger.h"
+
+#include "MLogManip.h"
+
+ClassImp(MReportTrigger);
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default construtor. Initialize identifier to "TRIGGER-REPORT"
+//
+MReportTrigger::MReportTrigger() : MReport("TRIGGER-REPORT"), fPrescalerRates(19)
+{
+    fName  = "MReportTrigger";
+    fTitle = "Class for TRIGGER-REPORT information";
+}
+
+// --------------------------------------------------------------------------
+//
+// Interprete the body of the TRIGGER-REPORT string
+//
+Int_t MReportTrigger::InterpreteBody(TString &str)
+{
+    str = str.Strip(TString::kLeading);
+
+    const Int_t ws = str.First(' ');
+    if (ws<=0)
+    {
+        *fLog << warn << "WARNING - Cannot determin name of trigger table." << endl;
+        return kCONTINUE;
+    }
+
+    TString tablename = str(0, ws);
+    str.Remove(0, ws);
+
+    Int_t len, n;
+
+    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-8-4/MagicSoft/Mars/mreport/MReportTrigger.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportTrigger.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/MReportTrigger.h	(revision 3781)
@@ -0,0 +1,48 @@
+#ifndef MARS_MReportTrigger
+#define MARS_MReportTrigger
+
+#ifndef MARS_MReport
+#include "MReport.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+class MReportTrigger : public MReport, public MCamEvent
+{
+private:
+    Float_t fL2BeforePrescaler; // L2 trigger rate before prescaler
+    Float_t fL2AfterPrescaler;  // L2 trigger rate after prescaler
+
+    TArrayF fPrescalerRates;    //[Hz] L2 prescaler rates
+    //TArrayF fRates;           //[Hz] currently undefined
+
+    Int_t InterpreteBody(TString &str);
+
+public:
+    MReportTrigger();
+
+    Float_t GetL2BeforePrescaler() const { return fL2BeforePrescaler; }
+    Float_t GetL2AfterPrescaler() const { return fL2AfterPrescaler; }
+
+    Bool_t GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type=0) const
+    {
+        if(idx>18)
+            return kFALSE;
+
+        val = fPrescalerRates[idx];
+        return kTRUE;
+    }
+
+    void DrawPixelContent(Int_t num) const
+    {
+    }
+
+    ClassDef(MReportTrigger, 1) // Class for TRIGGER-REPORT information
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/Makefile	(revision 3781)
@@ -0,0 +1,57 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Report
+
+#
+# Library name to creatre
+#
+LIB   = mreport.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mastro -I../mcamera -I../mgui
+# mgui - MCameraDC <MCamEvent>
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MReport.cc \
+           MReportCC.cc \
+           MReportRun.cc \
+           MReportDAQ.cc \
+           MReportHelp.cc \
+           MReportDrive.cc \
+           MReportCamera.cc \
+           MReportTrigger.cc \
+           MReportCurrents.cc \
+           MReportFileRead.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mreport/ReportLinkDef.h	(revision 3781)
@@ -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 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 MReportCamera+;
+#pragma link C++ class MReportTrigger+;
+#pragma link C++ class MReportCurrents+;
+
+#pragma link C++ class MReportHelp+;
+#pragma link C++ class MReportFileRead+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.cc	(revision 3781)
@@ -0,0 +1,117 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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, 2000-2004
+!
+!
+\* ======================================================================== */
+
+/////////////////////////////////////////////////////////////////////////////
+//
+// MArrivalTime
+//
+// Times are calculated using the TSpline5 Root Class
+// 
+/////////////////////////////////////////////////////////////////////////////
+#include "MArrivalTime.h"
+
+#include "MGeomCam.h"
+#include "MGeomPix.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MRawEvtPixelIter.h"
+#include "MRawEvtData.h"
+
+ClassImp(MArrivalTime);
+
+using namespace std;
+
+
+// --------------------------------------------------------------------------
+//
+// Creates an object containing the arrival time for each pixel in the event
+//
+MArrivalTime::MArrivalTime(const char *name, const char *title)
+{
+    fName  = name  ? name  : "MArrivalTime";
+    fTitle = title ? title : "Photons arrival times Information";
+}
+
+// -------------------------------------------------------------------------
+//
+// Sets every pixel arrival time to -1
+//
+void MArrivalTime::Reset()
+{
+  fData.Reset(-1);
+  fDataErr.Reset(-1);
+}
+
+void MArrivalTime::InitSize(Int_t i)
+{
+  fData.Set(i);
+  fDataErr.Set(i);
+}
+
+// -------------------------------------------------------------------------
+// 
+// Set the arrival time in one pixel
+//
+void MArrivalTime::SetTime(const Int_t i, const Float_t t)
+{
+    fData[i] = t;
+}
+      
+
+// -------------------------------------------------------------------------
+// 
+// Set the arrival time error in one pixel
+//
+void MArrivalTime::SetTimeErr(const Int_t i, const Float_t t)
+{
+    fDataErr[i] = t;
+}
+      
+// --------------------------------------------------------------------------
+//
+// Returns the arrival time value
+//
+Bool_t MArrivalTime::GetPixelContent(Double_t &val, Int_t idx, const MGeomCam &cam, Int_t type) const
+{
+    if (idx<0 || idx>=fData.GetSize())
+        return kFALSE;
+
+    switch (type)
+    {
+    case 0:
+    case 1:
+        val = fData[idx];
+        break;
+    }
+
+    return kTRUE;
+}
+
+void MArrivalTime::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MArrivalTime::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTime.h	(revision 3781)
@@ -0,0 +1,51 @@
+#ifndef MARS_MArrivalTime
+#define MARS_MArrivalTime
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+#ifndef MARS_MCamEvent
+#include "MCamEvent.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+#ifndef ROOT_TArrayS
+#include <TArrayS.h>
+#endif
+
+class MRawEvtData;
+
+class MArrivalTime : public MParContainer, public MCamEvent
+{
+private:
+  TArrayF fData;     // Stores the calibrated arrival times
+  TArrayF fDataErr;  // Stores the calibrated arrival time errors
+
+public:
+
+    MArrivalTime(const char *name=NULL, const char *title=NULL);
+    ~MArrivalTime() { }
+
+    void   Reset();
+    void   InitSize(Int_t i);
+
+    UInt_t GetSize() const { return fData.GetSize(); }
+
+    void SetTime(const Int_t i, const Float_t time);
+    void SetTimeErr(const Int_t i, const Float_t timeerr);    
+    
+    const TArrayF &GetData() const { return fData; }
+    const TArrayF &GetDataErr() const { return fDataErr; }
+
+    Double_t operator[](int i) { return fData[i]; }
+    Double_t operator()(int i) { return fDataErr[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(MArrivalTime, 0)    // class for an event containing the arrival times
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.cc	(revision 3781)
@@ -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): 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;
+}
+
+// --------------------------------------------------------------------------
+//
+// The ReInit searches for the following input containers:
+//  - MGeomCam
+//
+Bool_t MArrivalTimeCalc::ReInit(MParList *pList)
+{
+    MGeomCam *cam = (MGeomCam*)pList->FindObject(AddSerialNumber("MGeomCam"));
+    if (!cam)
+    {
+        *fLog << err << GetDescriptor() << ": No MGeomCam found... aborting." << endl;
+        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-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc.h	(revision 3781)
@@ -0,0 +1,43 @@
+#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);
+  Bool_t ReInit(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-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.cc	(revision 3781)
@@ -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;
+	}
+    }
+
+    // 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, deltatimehi, timelo, 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-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCalc2.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.cc	(revision 3781)
@@ -0,0 +1,163 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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;
+    default:
+	return kFALSE;
+    }
+    return val>=0;
+}
+
+void MArrivalTimeCam::DrawPixelContent(Int_t num) const
+{
+    *fLog << warn << "MArrivalTimeCam::DrawPixelContent - not available." << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimeCam.h	(revision 3781)
@@ -0,0 +1,67 @@
+#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 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, 0)	// Storage Container for the ArrivalTime in the camera
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.cc	(revision 3781)
@@ -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  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)
+  : fArrivalTimeHiGain(gkSignalInitializer),
+    fArrivalTimeHiGainError(gkSignalInitializer),
+    fArrivalTimeLoGain(gkSignalInitializer),
+    fArrivalTimeLoGainError(gkSignalInitializer),
+    fIsLoGainUsed(kFALSE),
+    fNumHiGainSaturated(0),
+    fNumLoGainSaturated(0)
+{
+  fName  = name  ? name  : "MArrivalTimePix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MArrivalTimePix::Clear(Option_t *o)
+{
+  fArrivalTimeHiGain      = gkSignalInitializer;
+  fArrivalTimeHiGainError = gkSignalInitializer;
+  fArrivalTimeLoGain      = gkSignalInitializer;
+  fArrivalTimeLoGainError = gkSignalInitializer;
+  
+  fIsLoGainUsed = kFALSE;
+
+  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 fArrivalTimeHiGain >= 0. || fArrivalTimeHiGainError >= 0.;
+}
+
+void MArrivalTimePix::SetGainSaturation(Bool_t sat, Byte_t higain, Byte_t logain) 
+{
+
+  fIsLoGainUsed = sat; 
+  fNumHiGainSaturated = higain; 
+  fNumLoGainSaturated = logain;
+}
+
+void MArrivalTimePix::Print(Option_t *o) const
+{
+    *fLog << " Signal: " << fArrivalTimeHiGain
+        << " +- " << fArrivalTimeHiGainError
+        << " LoGain? " << fIsLoGainUsed
+        << " Nr. Sat. Hi Gain: " <<  fNumHiGainSaturated
+        << " Nr. Sat. Lo Gain: " <<  fNumLoGainSaturated
+        << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MArrivalTimePix.h	(revision 3781)
@@ -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
+
+  Bool_t fIsLoGainUsed;
+  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 GetNumLoGainSaturated()          const { return fNumLoGainSaturated; }
+
+    Bool_t IsLoGainUsed() const { return fIsLoGainUsed; }
+    Bool_t IsValid() const;   
+
+    ClassDef(MArrivalTimePix, 0)	// Storage Container for ArrivalTime information of one pixel
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.cc	(revision 3781)
@@ -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/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractBlindPixel
+//
+//////////////////////////////////////////////////////////////////////////////
+#include "MExtractBlindPixel.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 "MExtractedSignalBlindPixel.h"
+
+ClassImp(MExtractBlindPixel);
+
+using namespace std;
+
+const Int_t  MExtractBlindPixel::fgBlindPixelIdx   = 559;
+const Byte_t MExtractBlindPixel::fgSaturationLimit = 254;
+const Byte_t MExtractBlindPixel::fgFirst =  3;
+const Byte_t MExtractBlindPixel::fgLast  = 16;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractBlindPixel::MExtractBlindPixel(const char *name, const char *title)
+    : fSaturationLimit(fgSaturationLimit)
+{
+  
+  fName  = name  ? name  : "MExtractBlindPixel";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  AddToBranchList("MRawEvtData.*");
+  
+  SetBlindPixelIdx();
+  SetSaturationLimit();
+  SetRange();
+}
+
+void MExtractBlindPixel::SetRange(Byte_t first, Byte_t last)
+{
+
+    fNumSamples = last-first+1;
+    fFirst      = first;
+    fLast       = last;
+
+    fSqrtSamples = TMath::Sqrt((Float_t)fNumSamples);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedBlindPixel
+//
+Int_t MExtractBlindPixel::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;
+    }
+
+    fBlindPixel = (MExtractedSignalBlindPixel*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalBlindPixel"));
+    if (!fBlindPixel)
+        return kFALSE;
+
+    fBlindPixel->SetUsedFADCSlices(fFirst, fLast);
+    fBlindPixel->SetBlindPixelIdx(fBlindPixelIdx);
+
+    return kTRUE;
+}
+
+// --------------------------------------------------------------------------
+//
+// 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();
+
+    pixel.Jump(fBlindPixelIdx);
+ 
+    const UInt_t nhigain = pixel.GetNumHiGainSamples();
+
+    Byte_t *ptr = pixel.GetHiGainSamples();
+    
+    //
+    // We need a dedicated signal extractor for the blind pixel
+    //
+    Int_t  diff  = 0;
+    UInt_t first = fFirst;
+    UInt_t last  = fLast;
+    UInt_t sat  = 0;
+
+    if (last > nhigain)
+      {
+        diff = last - nhigain;
+        last = nhigain;
+      }
+    
+    
+    Byte_t *start   = ptr + first - 1;
+    Byte_t *end     = ptr + last  - 1;
+    
+    ptr = start;
+    
+    Int_t sum = 0;
+    
+    while (ptr<=end)
+      {
+        sum += *ptr;
+
+        if (*ptr++ >= fSaturationLimit)
+          sat++;
+      }
+    
+    if (diff > 0)
+      {
+        ptr = pixel.GetLoGainSamples();
+        end = ptr + diff - 1;
+        
+        while (ptr<=end)
+          {
+
+            sum += *ptr;
+
+            if (*ptr++ >= fSaturationLimit)
+              sat++;
+
+          }
+      }
+    
+    fBlindPixel->SetExtractedSignal(sum);
+    fBlindPixel->SetNumSaturated(sat);
+    fBlindPixel->SetReadyToSave();
+
+    return kTRUE;
+}
+
+Int_t MExtractBlindPixel::PostProcess()
+{
+
+    MPedestalPix &pedpix  = (*fPedestals)[fBlindPixelIdx];    
+
+    if (&pedpix)
+    {
+	 fBlindPixel->SetPed      ( pedpix.GetPedestal()   * fNumSamples );
+	 fBlindPixel->SetPedErr   ( pedpix.GetPedestalRms()* fNumSamples / TMath::Sqrt((Float_t)fPedestals->GetTotalEntries()) );
+	 fBlindPixel->SetPedRms   ( pedpix.GetPedestalRms()* TMath::Sqrt((Float_t)fNumSamples) );
+	 fBlindPixel->SetPedRmsErr( fBlindPixel->GetPedErr()/2. );
+    }
+
+    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 MExtractBlindPixel::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fSaturationLimit!=fgSaturationLimit)
+    {
+        out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+        out << (int)fSaturationLimit << ");" << endl;
+    }
+
+    const Bool_t arg2 = fNumSamples+fFirst-1 != fgLast;
+    const Bool_t arg1 = arg2 || fFirst != fgFirst;
+
+    if (!arg1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetRange(";
+    out << (int)fFirst;
+    if (arg2)
+      out << ", " << (int)(fNumSamples+fFirst-1);
+    out << ");" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractBlindPixel.h	(revision 3781)
@@ -0,0 +1,62 @@
+#ifndef MARS_MExtractBlindPixel
+#define MARS_MExtractBlindPixel
+
+/////////////////////////////////////////////////////////////////////////////
+//                                                                         //
+// MExtractBlindPixel                                                        //
+//                                                                         //
+// 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 MRawEvtPixelIter;
+class MPedestalCam;
+class MExtractedSignalBlindPixel;
+class MExtractBlindPixel : public MTask
+{
+private:
+
+  static const Int_t  fgBlindPixelIdx;  
+  static const Byte_t fgSaturationLimit;
+  static const Byte_t fgFirst;
+  static const Byte_t fgLast;
+
+  MExtractedSignalBlindPixel  *fBlindPixel;   // Extracted signal of the Blind Pixel
+
+  MRawEvtData         *fRawEvt;       // raw event data (time slices)
+  MRawRunHeader       *fRunHeader;    // RunHeader information
+  MPedestalCam        *fPedestals;    // pointer to the pedestal information
+  
+  Byte_t  fFirst;
+  Byte_t  fLast;
+  Byte_t  fNumSamples;
+  Float_t fSqrtSamples;
+  Byte_t  fSaturationLimit;
+
+  Int_t  fBlindPixelIdx;
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  Int_t  PostProcess();
+  void   StreamPrimitive(ofstream &out) const;
+  
+public:
+
+  MExtractBlindPixel(const char *name=NULL, const char *title=NULL);
+
+  // Setters
+  void SetRange(const Byte_t first=fgFirst, const Byte_t last=fgLast);
+  void SetSaturationLimit(const Byte_t lim=fgSaturationLimit) { fSaturationLimit = lim; }
+  void SetBlindPixelIdx(  const  Int_t idx=fgBlindPixelIdx  ) { fBlindPixelIdx   = idx; }  
+
+  ClassDef(MExtractBlindPixel, 0) // Task to fill the Extracted BlindPixel Containers from raw data
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.cc	(revision 3781)
@@ -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): Markus Gaug, 02/2004 <mailto:markus@ifae.es>
+!
+!   Copyright: MAGIC Software Development, 2000-2004
+!
+!
+\* ======================================================================== */
+
+//////////////////////////////////////////////////////////////////////////////
+//
+//   MExtractPINDiode
+//
+//////////////////////////////////////////////////////////////////////////////
+#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     = 1;
+const Byte_t MExtractPINDiode::fgSaturationLimit = 254;
+const Byte_t MExtractPINDiode::fgFirst =  1;
+const Byte_t MExtractPINDiode::fgLast  = 30;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor. 
+//
+MExtractPINDiode::MExtractPINDiode(const char *name, const char *title)
+    : fSaturationLimit(fgSaturationLimit)
+{
+  
+  fName  = name  ? name  : "MExtractPINDiode";
+  fTitle = title ? title : "Task to extract the signal from the FADC slices";
+  
+  AddToBranchList("MRawEvtData.*");
+  
+  SetPINDiodeIdx();
+  SetSaturationLimit();
+  SetRange();
+}
+
+void MExtractPINDiode::SetRange(Byte_t first, Byte_t last)
+{
+
+    fNumSamples = last-first+1;
+    fFirst      = first;
+    fLast       = last;
+
+    fSqrtSamples = TMath::Sqrt((Float_t)fNumSamples);
+}
+
+// --------------------------------------------------------------------------
+//
+// The PreProcess searches for the following input containers:
+//  - MRawEvtData
+//  - MPedestalCam
+//
+// The following output containers are also searched and created if
+// they were not found:
+//
+//  - MExtractedPINDiode
+//
+Int_t MExtractPINDiode::PreProcess(MParList *pList)
+{
+    fRawEvt = (MRawEvtData*)pList->FindObject(AddSerialNumber("MRawEvtData"));
+    if (!fRawEvt)
+    {
+        *fLog << err << AddSerialNumber("MRawEvtData") << " not found... aborting." << endl;
+        return kFALSE;
+    }
+
+
+    fPINDiode = (MExtractedSignalPINDiode*)pList->FindCreateObj(AddSerialNumber("MExtractedSignalPINDiode"));
+    if (!fPINDiode)
+        return kFALSE;
+
+    fPINDiode->SetUsedFADCSlices(fFirst, fLast);
+
+    fPedestals = (MPedestalCam*)pList->FindObject(AddSerialNumber("MPedestalCam"));
+
+    if (!fPedestals)
+    {
+        *fLog << err << AddSerialNumber("MPedestalCam") << " not found... aborting" << endl;
+        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;
+}
+
+void MExtractPINDiode::FindSignal(Byte_t *ptr, Int_t size, UInt_t &sum, UInt_t &sum2, UInt_t &sat, UInt_t &max) const
+{
+
+  Byte_t *end = ptr + size;
+  
+  while (ptr<end)
+    {
+      sum  += *ptr;
+      sum2 += *ptr * *ptr;
+      if (*ptr > max)
+        max = *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);
+ 
+    UInt_t sum  = 0;
+    UInt_t sum2 = 0;
+    UInt_t sat  = 0;
+    UInt_t max  = 0;
+
+    FindSignal(pixel.GetHiGainSamples()+fFirst-1, 
+               fRawEvt->GetNumHiGainSamples(), 
+               sum, sum2, sat, max);
+    FindSignal(pixel.GetLoGainSamples(), 
+               fLast-fRawEvt->GetNumLoGainSamples(), 
+               sum, sum2, sat, max);
+    
+
+    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);
+
+    if (sat)
+      *fLog << warn << "WARNING - saturation occurred in the PIN Diode " << endl;
+
+    fPINDiode->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 MExtractPINDiode::StreamPrimitive(ofstream &out) const
+{
+    out << "   " << ClassName() << " " << GetUniqueName() << "(\"";
+    out << "\"" << fName << "\", \"" << fTitle << "\");" << endl;
+
+    if (fSaturationLimit!=fgSaturationLimit)
+    {
+        out << "   " << GetUniqueName() << ".SetSaturationLimit(";
+        out << (int)fSaturationLimit << ");" << endl;
+    }
+
+    const Bool_t arg2 = fNumSamples+fFirst-1 != fgLast;
+    const Bool_t arg1 = arg2 || fFirst != fgFirst;
+
+    if (!arg1)
+        return;
+
+    out << "   " << GetUniqueName() << ".SetRange(";
+    out << (int)fFirst;
+    if (arg2)
+      out << ", " << (int)(fNumSamples+fFirst-1);
+    out << ");" << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractPINDiode.h	(revision 3781)
@@ -0,0 +1,66 @@
+#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_MTask
+#include "MTask.h"
+#endif
+
+class MRawEvtData;
+class MRawRunHeader;
+
+class MPedestalCam;
+class MExtractedSignalPINDiode;
+class MExtractPINDiode : public MTask
+{
+private:
+
+  static const UInt_t fgPINDiodeIdx;  
+  static const Byte_t fgSaturationLimit;
+  static const Byte_t fgFirst;
+  static const Byte_t fgLast;
+
+  MPedestalCam              *fPedestals;    // Pedestals of all pixels in the camera
+  MExtractedSignalPINDiode  *fPINDiode;     // Extracted signal of the PIN Diode
+
+  MRawEvtData         *fRawEvt;       // raw event data (time slices)
+  MRawRunHeader       *fRunHeader;    // RunHeader information
+  
+  Byte_t  fFirst;
+  Byte_t  fLast;
+  Byte_t  fNumSamples;
+  Float_t fSqrtSamples;
+  Byte_t  fSaturationLimit;
+  UInt_t  fPINDiodeIdx;
+
+  Float_t fPedestal;
+  Float_t fPedRms;
+  
+  void   FindSignal(Byte_t *ptr, Int_t size, UInt_t &sum, UInt_t &sum2, UInt_t &sat, UInt_t &max) const;
+  
+  Int_t  PreProcess(MParList *pList);
+  Int_t  Process();
+  void   StreamPrimitive(ofstream &out) const;
+  
+public:
+
+  MExtractPINDiode(const char *name=NULL, const char *title=NULL);
+
+  // Setters
+  void SetRange(const Byte_t hifirst=fgFirst, 
+                const Byte_t hilast=fgLast);
+  void SetSaturationLimit(const Byte_t lim=fgSaturationLimit) { fSaturationLimit = lim; }
+  void SetPINDiodeIdx(    const UInt_t idx=fgPINDiodeIdx    ) { fPINDiodeIdx     = idx; }   
+
+  ClassDef(MExtractPINDiode, 0) // Task to fill the Extracted PINDiode Containers from raw data
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractSignal.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractSignal2.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal2.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal2.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractSignal2.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal2.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal2.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractSignal3.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal3.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal3.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractSignal3.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal3.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractSignal3.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.cc	(revision 3781)
@@ -0,0 +1,96 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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
+//
+// This is the storage container to hold informations about the extracted signal 
+// (offset) value of the calibration PIN Diode
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MExtractedSignalBlindPixel.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+ClassImp(MExtractedSignalBlindPixel);
+
+using namespace std;
+
+static const UInt_t gkSignalInitializer = 99999;
+
+// ------------------------------------------------------------------------
+//
+// MExtractedSignalBlindPixel 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 
+//
+MExtractedSignalBlindPixel::MExtractedSignalBlindPixel(const char* name, const char* title)
+{
+
+  fName  = name  ? name  : "MExtractedSignalBlindPixel";
+  fTitle = title ? title : "Container of the Extracted Signals";
+
+  Clear();
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MExtractedSignalBlindPixel::Clear(Option_t *o)
+{
+
+  fExtractedSignal    = gkSignalInitializer;
+
+  fPed                = gkSignalInitializer;;      
+  fPedErr             = gkSignalInitializer;;   
+  fPedRms             = gkSignalInitializer;;   
+  fPedRmsErr          = gkSignalInitializer;;  
+  
+  fNumSaturated       = 0;
+}
+
+void MExtractedSignalBlindPixel::SetUsedFADCSlices(const Byte_t first, const Byte_t num)   
+{
+  fFirst          = first; 
+  fNumFADCSamples = num;
+}
+
+
+Bool_t MExtractedSignalBlindPixel::IsValid() const
+{
+    return fExtractedSignal >= 0 && fExtractedSignal <  gkSignalInitializer;
+}
+
+void MExtractedSignalBlindPixel::Print(Option_t *o) const
+{
+  *fLog << " Signal: " << fExtractedSignal
+        << " Nr. Saturation: " <<  fNumSaturated
+        << endl;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalBlindPixel.h	(revision 3781)
@@ -0,0 +1,66 @@
+#ifndef MARS_MExtractedSignalBlindPixel
+#define MARS_MExtractedSignalBlindPixel
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include <TArrayI.h>
+
+class MExtractedSignalBlindPixel : public MParContainer
+{
+private:
+
+  UInt_t fExtractedSignal;    // mean value of the extracted signal
+
+  Byte_t fFirst;
+  Byte_t fNumFADCSamples;
+  Byte_t fNumSaturated;
+
+  Float_t fPed;
+  Float_t fPedErr;
+  Float_t fPedRms;
+  Float_t fPedRmsErr;
+
+  Int_t fBlindPixelIdx;
+
+public:
+
+  MExtractedSignalBlindPixel(const char* name=NULL, const char* title=NULL);
+
+  void Clear(Option_t *o="");
+  void Print(Option_t *o="") const;
+  
+  // Setter
+  void SetExtractedSignal(const UInt_t sig    )    { fExtractedSignal = sig;     }
+  void SetNumSaturated(   const Byte_t numsat )    { fNumSaturated    = numsat;  }
+  void SetUsedFADCSlices( const Byte_t first, const Byte_t num);
+  void SetNumFADCSamples( const Byte_t num    )    { fNumFADCSamples  = num;     }    
+
+  void SetPed(      const Float_t f )     { fPed       = f; }
+  void SetPedErr(   const Float_t f )     { fPedErr    = f; }
+  void SetPedRms(   const Float_t f )     { fPedRms    = f; }
+  void SetPedRmsErr(const Float_t f )     { fPedRmsErr = f; }
+
+  void SetBlindPixelIdx( const Int_t i)   { fBlindPixelIdx = i; }
+
+    // Getter
+  UInt_t GetExtractedSignal()    const { return fExtractedSignal; }
+  Byte_t GetNumFADCSamples()     const { return fNumFADCSamples;  }
+  Int_t  GetBlindPixelIdx()      const { return fBlindPixelIdx; }  
+
+  Bool_t IsValid() const;   
+
+  Float_t GetPed()       const { return fPed;       }
+  Float_t GetPedErr()    const { return fPedErr;    }
+  Float_t GetPedRms()    const { return fPedRms;    }
+  Float_t GetPedRmsErr() const { return fPedRmsErr; }
+
+  ClassDef(MExtractedSignalBlindPixel, 0)	// Storage Container for Extracted Signal of the blind pixel
+};
+
+#endif
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.cc	(revision 3781)
@@ -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): 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.)
+{
+    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));
+}
+
+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-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalCam.h	(revision 3781)
@@ -0,0 +1,71 @@
+#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;
+    Byte_t fFirstUsedSliceLoGain;
+
+    Byte_t fLastUsedSliceHiGain;
+    Byte_t fLastUsedSliceLoGain;
+
+    Float_t fUsedWindowHiGain;
+    Float_t fUsedWindowLoGain;
+    
+public:
+
+    MExtractedSignalCam(const char *name=NULL, const char *title=NULL);
+    ~MExtractedSignalCam();
+
+    void Print(Option_t *o="") const;
+    void Clear(Option_t *o="");
+    void SetLogStream(MLog *lg);
+
+    void InitSize(const UInt_t i);
+    Int_t GetSize() const;
+
+    Float_t GetNumUsedHiGainFADCSlices() const { return fUsedWindowHiGain; }
+    Float_t GetNumUsedLoGainFADCSlices() const { return fUsedWindowLoGain; }
+
+    Byte_t GetFirstUsedSliceHiGain() const    { return fFirstUsedSliceHiGain; }
+    Byte_t GetFirstUsedSliceLoGain() const    { return fFirstUsedSliceLoGain; }
+
+    Byte_t GetLastUsedSliceHiGain()  const    { return fLastUsedSliceHiGain; }
+    Byte_t GetLastUsedSliceLoGain()  const    { return fLastUsedSliceLoGain; }
+
+    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, 0)	// Storage Container for extracted signals in the camera
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPINDiode.h	(revision 3781)
@@ -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, 0)	// Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.cc	(revision 3781)
@@ -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  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)
+  : fExtractedSignalHiGain(gkSignalInitializer),
+    fExtractedSignalHiGainError(gkSignalInitializer),
+    fExtractedSignalLoGain(gkSignalInitializer),
+    fExtractedSignalLoGainError(gkSignalInitializer),
+    fLoGainUsed(kFALSE),
+    fNumHiGainSaturated(0),
+    fNumLoGainSaturated(0)
+{
+  fName  = name  ? name  : "MExtractedSignalPix";
+  fTitle = title ? title : "Container of the Extracted Signals";
+}
+
+// ------------------------------------------------------------------------
+//
+// Invalidate values
+//
+void MExtractedSignalPix::Clear(Option_t *o)
+{
+  fExtractedSignalHiGain      = gkSignalInitializer;
+  fExtractedSignalHiGainError = gkSignalInitializer;
+  fExtractedSignalLoGain      = gkSignalInitializer;
+  fExtractedSignalLoGainError = gkSignalInitializer;
+  
+  fLoGainUsed = kFALSE;
+
+  fNumHiGainSaturated = 0;
+  fNumLoGainSaturated = 0;
+}
+
+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 fExtractedSignalHiGain >= 0. || fExtractedSignalHiGainError >= 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-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/MExtractedSignalPix.h	(revision 3781)
@@ -0,0 +1,47 @@
+#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
+
+  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);
+
+    // 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; }
+
+    Bool_t IsLoGainUsed() const { return fLoGainUsed; }
+    Bool_t IsValid() const;   
+
+    ClassDef(MExtractedSignalPix, 0)	// Storage Container for Extracted Signal information of one pixel
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/Makefile	(revision 3781)
@@ -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
+
+#
+# Library name to creatre
+#
+LIB   = msignal.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES =  -I. -I../mbase -I../mgui -I../mraw -I../manalysis \
+            -I../mgeom -I../mtools
+
+# mgui (MCamEvent):         MExtractSignalCam
+# mgeom(MGeomCam):          MArrivalTime
+# mtools(MCubicSpline):     MArrivalTime
+# mraw (MRawEvtData):       MExtractSignal
+# manalysis (MPedestalCam): MExtractSignal
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MExtractedSignalCam.cc \
+           MExtractedSignalPix.cc \
+           MExtractSignal.cc \
+           MExtractSignal2.cc \
+           MExtractSignal3.cc \
+	   MExtractPINDiode.cc \
+	   MExtractedSignalPINDiode.cc \
+	   MExtractBlindPixel.cc \
+	   MExtractedSignalBlindPixel.cc \
+           MArrivalTime.cc \
+           MArrivalTimeCalc.cc \
+           MArrivalTimeCalc2.cc \
+           MArrivalTimeCam.cc \
+	   MArrivalTimePix.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalIncl.h	(revision 3781)
@@ -0,0 +1,7 @@
+#ifndef __CINT__
+
+#include <TArrayC.h>
+#include "MArrayB.h"
+#include "MArrayS.h"
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msignal/SignalLinkDef.h	(revision 3781)
@@ -0,0 +1,26 @@
+#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 MExtractSignal+;
+#pragma link C++ class MExtractSignal2+;
+#pragma link C++ class MExtractSignal3+;
+
+#pragma link C++ class MExtractPINDiode++;
+#pragma link C++ class MExtractedSignalPINDiode++;
+#pragma link C++ class MExtractBlindPixel++;
+#pragma link C++ class MExtractedSignalBlindPixel++;
+
+#pragma link C++ class MArrivalTimeCam;
+#pragma link C++ class MArrivalTimePix;
+#pragma link C++ class MArrivalTime+;
+#pragma link C++ class MArrivalTimeCalc+;
+#pragma link C++ class MArrivalTimeCalc2+;
+
+
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.cc	(revision 3781)
@@ -0,0 +1,534 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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.
+//
+////////////////////////////////////////////////////////////////////////
+#include "MSQLServer.h"
+
+#include <iostream>
+#include <iomanip>
+#include <stdlib.h>
+
+#include <TROOT.h>
+
+#include <TH1.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]);
+
+    //cout << "Column Type: " << desc << endl;
+
+    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++;
+    }
+
+    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) const /*FOLD00*/
+{
+    cout << "+" << setfill('-');
+    for (int i=0; i<max.GetSize(); i++)
+        cout << setw(max[i]+1) << "-" << "-+";
+    cout << endl;
+}
+
+void MSQLServer::PrintTable(TSQLResult *res) const /*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);
+    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);
+}
+
+TSQLResult *MSQLServer::Query(const char *sql) /*FOLD00*/
+{
+    return fType==kIsServer ? fServ->Query(sql) : NULL;
+}
+
+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() : "";
+}
+
+void MSQLServer::Init(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    fServ = TSQLServer::Connect(connection, user, password);
+    if (fServ)
+    {
+        gROOT->GetListOfBrowsables()->Add(this, connection);
+        fType = kIsServer;
+    }
+    else
+        fType = kIsZombie;
+
+    fList.SetOwner();
+}
+
+MSQLServer::MSQLServer(const char *connection, const char *user, const char *password) /*FOLD00*/
+{
+    Init(connection, user, password);
+}
+
+MSQLServer::MSQLServer(const char *u) /*FOLD00*/
+{
+    TString url(u);
+
+    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;
+
+    const TString user = url(pos1, pos2-pos1-1);
+    const TString pasw = url(pos2, pos3-pos2);
+
+    url.Remove(pos1, pos3+1-pos1);
+
+    Init(url, user, pasw);
+
+}
+
+MSQLServer::~MSQLServer() /*FOLD00*/
+{
+    Close();
+    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)
+        return (PrintError("GetEntry - Number of columns != 1", query), "");
+
+    if (res->GetRowCount()>1)
+        return (PrintError("GetEntry - Number of rows > 1", query), "");
+
+    if (res->GetRowCount()==0)
+        return "";
+
+    const char *fld = res->Next()->GetField(0);
+    if (!fld)
+        return (PrintError("GetEntry - Entry is empty", query), "");
+
+    return TString(fld);
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSQLServer.h	(revision 3781)
@@ -0,0 +1,138 @@
+#ifndef MARS_MSQLServer
+#define MARS_MSQLServer
+
+#ifndef ROOT_TList
+#include <TList.h>
+#endif
+
+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;
+
+    void PrintLine(const TArrayI &max) const;
+    void PrintTable(TSQLResult *res) 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); }
+
+    const char *GetName() const
+    {
+        switch (fType)
+        {
+        case kIsDataBase: return GetNameDataBase();
+        case kIsTable:    return GetNameTable();
+        case kIsColumn:   return GetNameColumn();
+        default:          return "n/a";
+        }
+    }
+
+    void Init(const char *connection, const char *user, const char *password);
+
+public:
+    MSQLServer(TSQLServer *serv, const char *dbname=0, const char *tname=0, const char *col=0)
+        : fServ(serv), fDataBase(dbname), fTable(tname), fColumn(col)
+    {
+        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();
+
+    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();
+
+    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-8-4/MagicSoft/Mars/msql/MSqlInsertRun.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSqlInsertRun.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSqlInsertRun.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msql/MSqlInsertRun.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSqlInsertRun.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/MSqlInsertRun.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/msql/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/Makefile	(revision 3781)
@@ -0,0 +1,48 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Sql
+
+#
+# Library name to creatre
+#
+LIB   = msql.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = \
+	MSQLServer.cc \
+	MSqlInsertRun.cc
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/msql/SqlLinkDef.h	(revision 3781)
@@ -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 MSqlInsertRun+;
+
+#pragma link C++ class MSQLColumn+;
+#pragma link C++ class MSQLServer+;
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/Changelog
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/Changelog	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/Changelog	(revision 3781)
@@ -0,0 +1,19 @@
+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 -*-*-
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.cc	(revision 3781)
@@ -0,0 +1,231 @@
+////////////////////////////////////////////////////////////////////////////
+// Input Containers:
+//   MGeomCam
+//   MCerPhotEvt
+//   MPedestalCam
+//
+//  Output Containers:
+//   MIslands
+//
+/////////////////////////////////////////////////////////////////////////////
+#include "MIslandCalc.h"
+
+#include <stdlib.h>       // atof					  
+#include <fstream>        // ofstream, SavePrimitive
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MIslands.h"
+
+#include "MParList.h"
+
+//#include "MImgCleanStd.h"
+
+#include "MLog.h"
+#include "MLogManip.h"
+
+#include "MGeomPix.h"
+#include "MGeomCam.h"
+
+#include "MCerPhotPix.h"
+#include "MCerPhotEvt.h"
+
+#include "MPedestalCam.h"
+#include "MPedestalPix.h"
+
+
+ClassImp(MIslandCalc);
+
+
+using namespace std;
+
+// --------------------------------------------------------------------------
+//
+// Default constructor.
+//
+MIslandCalc::MIslandCalc(const char *name, const char *title)    
+  : fIsl(NULL)
+{
+    fName  = name  ? name  : "MIslandCalc";
+    fTitle = title ? title : "Calculate island parameters";
+}
+
+
+
+Int_t MIslandCalc::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;
+      }
+    
+    
+    fIsl = (MIslands*)pList->FindCreateObj(AddSerialNumber("MIslands"));
+    if (!fIsl)
+      return kFALSE;
+
+    return kTRUE;
+}
+
+
+//tries to clean a bit more the image avoiding noisy islands
+ 
+Int_t MIslandCalc::Process()
+{
+
+  Float_t  noise;
+  Float_t  signal;
+
+  Int_t    npix = 577;
+  Int_t    sflag;
+  Int_t    control;
+  
+  Int_t    nvect = 0;
+  Int_t    fIslNum = 0;
+  Float_t  fSigToNoise[30];
+
+  Int_t    vect[100][577];
+  Int_t    kk[577];
+  
+  for(Int_t m = 0; m < 50 ; m++)
+    for(Int_t n = 0; n < 577 ; n++)
+      vect[m][n] = 0;
+  
+  for(Int_t n = 0; n < 577 ; n++)
+    kk[n] = 0;
+   
+  // loop over all pixels
+  for(Int_t idx=0 ; idx<npix ; idx++)
+    { 
+      const MGeomPix &gpix  = (*fCam)[idx];
+      const Int_t    nnmax  = gpix.GetNumNeighbors();
+      
+      if(idx<0 || idx==npix)
+	{
+	  cout << "Pixel (software) index out of range [0-576]. Available number of pixels=" << npix << endl;
+	  return 1;
+	}
+      
+   
+      if(fEvt->IsPixelCore(idx) || fEvt->IsPixelUsed(idx)) 
+     	{
+	  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;	     
+	    }
+	  
+	}
+    }
+  
+  fIslNum = nvect;
+  
+  // Repeated Chain Corrections
+  for(Int_t i = 1; i <= nvect; i++)
+    {
+      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; 
+		  //cout << " two vectors coincide... "<< endl;
+		  break;
+		}
+	    }
+	  if (control == 1)
+	    {
+	      for(Int_t k = 0; k < npix; k++)
+		{
+		  if(vect[j][k] == 1)
+		    vect[i][k] = 1;
+		  vect[j][k] = 0;
+		}	
+	      fIslNum = fIslNum-1;	    
+	    }
+	}
+    }
+  
+  cout << " Let me see..." << endl;
+  cout << " Number of vectors: " << nvect << endl;
+  cout << " Number of islands: " << fIslNum << endl;      
+  
+  //examine each island...
+
+  Int_t fPixNum[30];
+
+  for(Int_t i = 1; i<=fIslNum ; i++)
+    {
+      signal = 0;
+      noise = 0;
+      fPixNum[i] = 0;
+      for(Int_t idx=0 ; idx<npix ; idx++)
+	{
+	  const MCerPhotPix &pix = (*fEvt)[idx];
+	  const MPedestalPix &ped  = (*fPed)[idx];
+
+	  if (vect[i][idx]==1){
+
+	    fPixNum[i]++;
+	    signal += pix.GetNumPhotons() * (fCam->GetPixRatio(idx));
+	    noise += pow(ped.GetPedestalRms(),2);
+
+	  }	
+	}
+
+      cout << "Signal: " << signal<<endl;
+      cout << "Noise: " << noise << endl;  
+      fSigToNoise[i] = (Float_t)signal/(Float_t)sqrt(noise);
+
+      fIsl->SetIslNum(fIslNum);
+      fIsl->SetPixNum(i,fPixNum[i]);
+      fIsl->SetSigToNoise(i,fSigToNoise[i]);
+
+      cout << " Island Num " << i << endl;
+      cout << " Pixel Number in the island: " << fPixNum[i] << endl;
+      cout << " Signal to Noise of the island : " << fSigToNoise[i] << endl;
+    	
+    }
+
+  return 1;
+}
+
+  
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslandCalc.h	(revision 3781)
@@ -0,0 +1,38 @@
+#ifndef MARS_MIslandCalc
+#define MARS_MIslandCalc
+
+#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 MIslands;
+
+class MIslandCalc : public MGTask
+{
+ private:
+    const MGeomCam    *fCam;        //!
+    MCerPhotEvt       *fEvt;        //!
+    MSigmabar         *fSgb;        //!
+    MPedestalCam      *fPed;        //!
+
+    MIslands          *fIsl;        //!    output container to store result
+   
+    Int_t PreProcess(MParList *plist);
+    Int_t Process();
+           
+ public:
+    MIslandCalc(const char *name=NULL, const char *title=NULL);
+
+    ClassDef(MIslandCalc, 0)        // task doing the image cleaning
+}; 
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.cc	(revision 3781)
@@ -0,0 +1,25 @@
+#include "MIslands.h"
+
+ClassImp(MIslands);
+
+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";
+
+}
+
+// --------------------------------------------------------------------------
+//
+// Destructor.
+//
+MIslands::~MIslands()
+{
+}
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MIslands.h	(revision 3781)
@@ -0,0 +1,39 @@
+#ifndef MARS_MIslands
+#define MARS_MIslands
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#ifndef ROOT_TArrayF
+#include <TArrayF.h>
+#endif
+
+#ifndef ROOT_TArrayI
+#include <TArrayI.h>
+#endif
+
+
+class MIslands : public MParContainer
+{
+private:
+    // for description see MIslands.cc
+    Int_t fIslNum;                    //    number of islands
+    Int_t fPixNum[30];                //    number of pixels in the island
+    Float_t fSigToNoise[30] ;         //    signal to noise of the island
+
+public:
+    MIslands(const char *name=NULL, const char *title=NULL);
+    ~MIslands();
+
+    Int_t    GetIslNum() const                        { return fIslNum; }
+    Int_t    GetPixNum(Int_t i) const                 { return fPixNum[i]; }
+    Float_t  GetSigToNoise(Int_t i) const             { return fSigToNoise[i]; } 
+    void     SetIslNum(Int_t i)                       { fIslNum = i; }
+    void     SetPixNum(Int_t i, Int_t j)              { fPixNum[i] = j; }
+    void     SetSigToNoise(Int_t i, Float_t m)        { fSigToNoise[i] = m; }
+   
+    ClassDef(MIslands, 1) // Storage Container for Island Parameters
+};
+
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPObject.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPObject.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPObject.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/MVPObject.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPObject.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPObject.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/MVPPlotter.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPPlotter.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPPlotter.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/MVPPlotter.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPPlotter.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPPlotter.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/MVPTime.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPTime.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPTime.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/MVPTime.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPTime.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/MVPTime.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtemp/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/Makefile	(revision 3781)
@@ -0,0 +1,51 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Temp
+
+#
+# Library name to creatre
+#
+LIB   = mtemp.a
+
+#
+#  connect the include files defined in the config.mk file
+#
+INCLUDES = -I. -I../mbase -I../mraw -I../manalysis -I../mmc \
+	   -I../mgui -I../mgeom -I../mdata -I../mhist -I../../slalib
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = \
+	MObservatoryLocation.cc \
+	MVPObject.cc \
+	MVPPlotter.cc \
+	MVPTime.cc 
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempIncl.h	(revision 3781)
@@ -0,0 +1,5 @@
+#ifndef __CINT__
+
+#include <slalib.h>
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtemp/TempLinkDef.h	(revision 3781)
@@ -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 MObservatoryLocation+;
+#pragma link C++ class MVPObject+;
+#pragma link C++ class MVPPlotter+;
+#pragma link C++ class MVPTime+;
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MChisqEval.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MChisqEval.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MChisqEval.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MChisqEval.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MChisqEval.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MChisqEval.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MCubicCoeff.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicCoeff.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicCoeff.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MCubicCoeff.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicCoeff.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicCoeff.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MCubicSpline.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicSpline.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicSpline.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MCubicSpline.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicSpline.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MCubicSpline.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MFFT.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MFFT.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MFFT.cc	(revision 3781)
@@ -0,0 +1,983 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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!                                //
+//                                                                          //
+//////////////////////////////////////////////////////////////////////////////
+
+#include "MFFT.h"
+
+#include <TMath.h>
+
+#include "MLog.h"
+#include "MLogManip.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;
+}
+
+
+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 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-8-4/MagicSoft/Mars/mtools/MFFT.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MFFT.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MFFT.h	(revision 3781)
@@ -0,0 +1,85 @@
+#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 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);
+
+  TArrayF*  RealFunctionSpectrum(const TArrayF *data);
+  
+  ClassDef(MFFT,0)  // Class to perform a Fast Fourier Transform
+};
+    
+#endif
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.cc	(revision 3781)
@@ -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): 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 <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-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MHSimulatedAnnealing.h	(revision 3781)
@@ -0,0 +1,51 @@
+#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 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-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.cc	(revision 3781)
@@ -0,0 +1,628 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that 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 "MHSimulatedAnnealing.h"
+
+#include <fstream>
+#include <iostream>
+
+#include <TRandom.h>
+
+#include "MLog.h"
+#include "MLogManip.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-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MSimulatedAnnealing.h	(revision 3781)
@@ -0,0 +1,106 @@
+#ifndef MARS_MSimulatedAnnealing
+#define MARS_MSimulatedAnnealing
+
+#ifndef MARS_MAGIC
+#include "MAGIC.h"
+#endif
+
+#ifndef ROOT_TMatrix
+#include <TMatrix.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-8-4/MagicSoft/Mars/mtools/MTFillMatrix.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTFillMatrix.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTFillMatrix.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MTFillMatrix.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTFillMatrix.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTFillMatrix.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MTMinuit.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTMinuit.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTMinuit.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MTMinuit.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTMinuit.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MTMinuit.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicCivilization.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicCivilization.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicCivilization.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicCivilization.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicCivilization.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicCivilization.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicDomino.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicDomino.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicDomino.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicDomino.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicDomino.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicDomino.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicReversi.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicReversi.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicReversi.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicReversi.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicReversi.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicReversi.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicShow.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicShow.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicShow.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicShow.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicShow.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicShow.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicSnake.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicSnake.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicSnake.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MagicSnake.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicSnake.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MagicSnake.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/Makefile	(revision 3781)
@@ -0,0 +1,63 @@
+##################################################################
+#
+#   makefile
+# 
+#   for the MARS software
+#
+##################################################################
+include ../Makefile.conf.$(OSTYPE)
+include ../Makefile.conf.general
+
+#
+# Handling name of the Root Dictionary Files
+#
+CINT  = Tools
+
+#
+# Library name to creatre
+#
+LIB   = mtools.a
+
+#
+#  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)
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+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
+
+
+SRCS    = $(SRCFILES)
+HEADERS = $(SRCFILES:.cc=.h)
+OBJS    = $(SRCFILES:.cc=.o) 
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
+
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MineSweeper.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MineSweeper.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MineSweeper.cc	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/MineSweeper.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MineSweeper.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/MineSweeper.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/mtools/ToolsIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/ToolsIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/ToolsIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/ToolsLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/ToolsLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/mtools/ToolsLinkDef.h	(revision 3781)
@@ -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-8-4/MagicSoft/Mars/readdaq.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/readdaq.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/readdaq.cc	(revision 3781)
@@ -0,0 +1,197 @@
+#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);
+
+    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");
+
+    tasks.AddToList(&print0);
+    tasks.AddToList(&print1);
+    tasks.AddToList(&print2);
+    if (kPrintArray)
+        tasks.AddToList(&print3);
+    tasks.AddToList(&print4);
+
+    //
+    // 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-8-4/MagicSoft/Mars/readraw.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/readraw.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/readraw.cc	(revision 3781)
@@ -0,0 +1,218 @@
+#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;
+    MRawCrateArray *evtcrate  = NULL;
+    MMcEvt         *evtmc     = NULL;
+    MMcTrig        *trigmc    = NULL;
+
+    EnableBranch(evttree, "MRawEvtHeader",  &evtheader);
+    EnableBranch(evttree, "MTime",          &evttime);
+    EnableBranch(evttree, "MRawEvtData",    &evtdata);
+    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();
+        if (evtheader)
+            evtheader->Print();
+        if (evttime)
+            evttime->Print();
+        if (evtcrate)
+            evtcrate->Print();
+        if (evtdata)
+            evtdata->Print(kDecimal?"dec":"hex");
+
+        gLog << endl;
+    } 
+    
+    // end of small readin program
+
+    return 0;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/star.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/star.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/star.cc	(revision 3781)
@@ -0,0 +1,481 @@
+#include <TSystem.h>
+
+#include "MParList.h"
+#include "MTaskList.h"
+#include "MEvtLoop.h"
+/*'
+#include "MLog.h"
+ */
+#include "MLogManip.h"
+
+#include "MArgs.h"
+
+#include "MArray.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 "MWriteRootFile.h"
+#include "MFDataMember.h"
+#include "MFillH.h"
+#include "MReportDrive.h"    // PRELIMINARY:
+//#include "MPointingPos.h"    // PRELIMINARY:
+//#include "MPointingPosCalc.h"
+
+using namespace std;
+
+//////////////////////////////////////////////////////////////////////////////
+//
+// This is an easy implementation of the Star process
+// (as compilable prog)
+//
+//////////////////////////////////////////////////////////////////////////////
+
+static void StartUpMessage()
+{
+    gLog << all << endl;
+
+    //                1         2         3         4         5
+    //       12345678901234567890123456789012345678901234567890
+    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()
+{
+    gLog << all << endl;
+    gLog << "Sorry the usage is:" << endl;
+    gLog << "   star [-a0] [-vn] [-cn] inputfile[.root] outputfile[.root]" << endl << endl;
+    gLog << "     input file: Merpped or MC root file." << endl;
+    gLog << "     ouput file: Star-file (image parameter file)" << endl;
+    gLog << "     -a0: Do not use Ansii codes." << endl;
+    gLog << "     -cn: Compression level n=1..9 [default=2]" << endl;
+    gLog << "     -vn: Verbosity level n [default=2]" << endl;
+    gLog << "     -u1: Update File (instead of Recreate)" << endl;
+    gLog << "     -tn: Telescope Serial Number n [default=0]" << endl << endl;
+    gLog << " -> Further setup is not possible at the moment, please use" << endl;
+    gLog << "    the star.C root macro instead. Using an input card will" << endl;
+    gLog << "    be implemented in the future." << endl << endl;
+}
+
+class MJStar : public MParContainer
+{
+private:
+    TString fInputFile;
+    TString fOutputFile;
+
+    Bool_t fIsUpdate;
+    Byte_t fComprLevel;
+
+    Byte_t fSerialIdx;
+
+    Bool_t CheckFiles()
+    {
+        if (fOutputFile.IsNull())
+        {
+            fOutputFile = fInputFile;
+
+            if (fOutputFile.EndsWith(".raw"))
+                fOutputFile = fOutputFile(0, fOutputFile.Length()-4);
+
+            if (fOutputFile.EndsWith(".rep"))
+                fOutputFile = fOutputFile(0, fOutputFile.Length()-4);
+
+            if (fOutputFile.EndsWith(".txt"))
+                fOutputFile = fOutputFile(0, fOutputFile.Length()-4);
+        }
+
+        if (fInputFile.IsNull())
+        {
+            *fLog << err << "Sorry, no input file." << endl;
+            return kFALSE;
+        }
+
+        if (fOutputFile.IsNull())
+        {
+            *fLog << err << "Sorry, no output file." << endl;
+            return kFALSE;
+        }
+
+        if (!fInputFile.EndsWith(".root"))
+            fInputFile += ".root";
+
+        if (!fOutputFile.EndsWith(".root"))
+            fOutputFile += ".root";
+
+        //
+        // check whether the given files are OK.
+        //
+        if (gSystem->AccessPathName(fInputFile, kFileExists))
+        {
+            *fLog << err << "Sorry, the input file '" << fInputFile << "' doesn't exist." << endl;
+            return kFALSE;
+        }
+
+        if (!gSystem->AccessPathName(fOutputFile, kFileExists))
+        {
+            if (fIsUpdate)
+                gLog << warn << "Warning: File doesn't '" << fOutputFile << "' exist... recreating." << endl;
+        }
+
+        if (fIsUpdate || gSystem->AccessPathName(fOutputFile, kFileExists))
+            if (!gSystem->AccessPathName(fOutputFile, kWritePermission))
+        {
+            gLog << err << "Sorry, you don't have write permission for '" << fOutputFile << "'." << endl;
+            return kFALSE;
+        }
+        return kTRUE;
+    }
+
+public:
+    MJStar(const char *name=0, const char *title=0)
+        : fIsUpdate(kFALSE), fComprLevel(1), fSerialIdx(0)
+    {
+        fName  = name;
+        fTitle = title;
+    }
+
+    void SetInputFile(const char *f)  { fInputFile  = f; }
+    void SetOutputFile(const char *f) { fOutputFile = f; }
+    void SetSerialIdx(Byte_t i)       { fSerialIdx  = i; }
+    void SetComprLevel(Byte_t l)      { fComprLevel = l; }
+    void SetUpdate(Bool_t u=kTRUE)    { fIsUpdate   = u; }
+
+    Bool_t Process()
+    {
+        if (!CheckFiles())
+            return kFALSE;
+
+        //
+        // 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);
+
+        // PRELIMINARY:
+        /*
+         MReportDrive rep;
+         plist.AddToList(&rep);
+         MPointingPos pos;
+         plist.AddToList(&pos);
+         */
+
+        //
+        // Now setup the tasks and tasklist:
+        // ---------------------------------
+        //
+        MReadMarsFile read("Events", fInputFile);
+        read.DisableAutoScheme();
+
+        MGeomApply        apply;
+        MMcPedestalCopy   pcopy;
+        MMcPedestalNSBAdd pnsb;
+
+        //MPointingPosCalc  pcalc;
+
+        MCerPhotCalc      ncalc;
+        MCerPhotAnal2     nanal;
+
+        MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);
+        MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);
+
+        ncalc.SetFilter(&f1);
+        nanal.SetFilter(&f2);
+
+        MBlindPixelCalc   blind;
+        MSigmabarCalc     sgcal;
+        //MFillH            fills("MHSigmaTheta",  "", "FillSigmaTheta");
+        //MFillH            fillb("MHBlindPixels", "", "FillBlindPixels");
+        MImgCleanStd      clean;
+        MHillasCalc       hcalc;
+        MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+        MWriteRootFile    write(fOutputFile, fIsUpdate?"UPDATE":"RECREATE", "Star output", fComprLevel);
+
+        tlist.AddToList(&read);
+        tlist.AddToList(&f1);
+        tlist.AddToList(&f2);
+        tlist.AddToList(&apply);
+        tlist.AddToList(&pcopy);
+        tlist.AddToList(&pnsb);
+        //tlist.AddToList(&pcalc);
+        tlist.AddToList(&ncalc);
+        tlist.AddToList(&nanal);
+        tlist.AddToList(&blind);
+        tlist.AddToList(&sgcal);
+        //tlist.AddToList(&fills);
+        //tlist.AddToList(&fillb);
+        tlist.AddToList(&clean);
+        tlist.AddToList(&hcalc);
+        tlist.AddToList(&scalc);
+        tlist.AddToList(&write);
+
+        //
+        // Set the serial number for all tasks in the current tasklist
+        //
+        tlist.SetSerialNumber(fSerialIdx);
+
+        //
+        // Setup tasks
+        //
+        blind.SetUseInterpolation();
+
+        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(write.AddSerialNumber("MHSigmaTheta"), "RunHeaders");
+        if (!fIsUpdate)
+        {
+            write.AddContainer("MRawRunHeader", "RunHeaders");
+            write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+        }
+
+        //
+        // Create and set up the eventloop
+        //
+        MEvtLoop evtloop;
+        evtloop.SetParList(&plist);
+
+        //
+        // Execute your analysis
+        //
+        if (!evtloop.Eventloop())
+        {
+            gLog << err << "ERROR: Star eventloop failed!" << endl;
+            return kFALSE;
+        }
+
+        tlist.PrintStatistics();
+
+        //plist.FindObject("MHSigmaTheta")->Write();
+        //plist.FindObject("MHBlindPixels")->Write();
+
+        gLog << all << "Star finished successfull!" << endl;
+
+        return kTRUE;
+    }
+//    ClassDef(MJStar, 0)
+};
+
+//ClassImp(MJStar);
+
+
+int main(const int argc, char **argv)
+{
+    StartUpMessage();
+
+    //
+    // Evaluate arguments
+    //
+    MArgs arg(argc, argv);
+
+    //
+    // 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  kComprlvl = arg.HasOption("-c") ? arg.GetIntAndRemove("-c") : 1;
+    const int  kTelIndex = arg.HasOption("-t") ? arg.GetIntAndRemove("-t") : 0;
+    const bool kUpdate   = arg.HasOption("-u") && arg.GetIntAndRemove("-u")==1;
+
+    //
+    // check for the right usage of the program
+    //
+    if (arg.GetNumArguments()!=2)
+    {
+        Usage();
+        return -1;
+    }
+
+    //
+    // Initialize Non-GUI (batch) mode
+    //
+    gROOT->SetBatch();
+
+    MArray::Class()->IgnoreTObjectStreamer();
+    MParContainer::Class()->IgnoreTObjectStreamer();
+
+    MJStar star;
+    star.SetInputFile(arg.GetArgumentStr(0));
+    star.SetOutputFile(arg.GetArgumentStr(1));
+    star.SetComprLevel(kComprlvl);
+    star.SetSerialIdx(kTelIndex);
+    star.SetUpdate(kUpdate);
+
+    if (!star.Process())
+    {
+        gLog << err << "Star failed!" << endl;
+        return -1;
+    }
+
+    gLog << inf << "Star finished successfull!" << endl;
+
+    return 0;
+/*
+    //
+    // This is to make argv[i] more readable inside the code
+    //
+    TString kNamein  = arg.GetArgumentStr(0);
+    TString kNameout = arg.GetArgumentStr(1);
+
+    if (!kNamein.EndsWith(".root"))
+        kNamein += ".root";
+
+    if (!kNameout.EndsWith(".root"))
+        kNameout += ".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;
+    }
+
+    if (!gSystem->AccessPathName(kNameout, kFileExists))
+    {
+        if (kUpdate)
+            gLog << warn << "Warning: File doesn't '" << kNameout << "' exist... recreating." << endl;
+    }
+
+    if (kUpdate || gSystem->AccessPathName(kNameout, kFileExists))
+        if (!gSystem->AccessPathName(kNameout, kWritePermission))
+        {
+            gLog << err << "Sorry, you don't have write permission for '" << kNameout << "'." << endl;
+            return -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);
+
+    // PRELIMINARY:
+    // MReportDrive rep;
+    // plist.AddToList(&rep);
+    // MPointingPos pos;
+    // plist.AddToList(&pos);
+
+    //
+    // Now setup the tasks and tasklist:
+    // ---------------------------------
+    //
+    MReadMarsFile read("Events", kNamein);
+    read.DisableAutoScheme();
+
+    MGeomApply        apply;
+    MMcPedestalCopy   pcopy;
+    MMcPedestalNSBAdd pnsb;
+
+    //MPointingPosCalc  pcalc;
+
+    MCerPhotCalc      ncalc;
+    MCerPhotAnal2     nanal;
+
+    MFDataMember f1("MRawRunHeader.fRunType", '>', 255.5);
+    MFDataMember f2("MRawRunHeader.fRunType", '<', 255.5);
+
+    ncalc.SetFilter(&f1);
+    nanal.SetFilter(&f2);
+
+    MBlindPixelCalc   blind;
+    MSigmabarCalc     sgcal;
+    //MFillH            fills("MHSigmaTheta",  "", "FillSigmaTheta");
+    //MFillH            fillb("MHBlindPixels", "", "FillBlindPixels");
+    MImgCleanStd      clean;
+    MHillasCalc       hcalc;
+    MHillasSrcCalc    scalc; // !!Preliminary!! Will be removed later!
+    MWriteRootFile    write(kNameout, kUpdate?"UPDATE":"RECREATE", "Star output", kComprlvl);
+
+    tlist.AddToList(&read);
+    tlist.AddToList(&f1);
+    tlist.AddToList(&f2);
+    tlist.AddToList(&apply);
+    tlist.AddToList(&pcopy);
+    tlist.AddToList(&pnsb);
+    //tlist.AddToList(&pcalc);
+    tlist.AddToList(&ncalc);
+    tlist.AddToList(&nanal);
+    tlist.AddToList(&blind);
+    tlist.AddToList(&sgcal);
+    //tlist.AddToList(&fills);
+    //tlist.AddToList(&fillb);
+    tlist.AddToList(&clean);
+    tlist.AddToList(&hcalc);
+    tlist.AddToList(&scalc);
+    tlist.AddToList(&write);
+
+    //
+    // Set the serial number for all tasks in the current tasklist
+    //
+    tlist.SetSerialNumber(kTelIndex);
+
+    //
+    // Setup tasks
+    //
+    blind.SetUseInterpolation();
+
+    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(write.AddSerialNumber("MHSigmaTheta"), "RunHeaders");
+    if (!kUpdate)
+    {
+        write.AddContainer("MRawRunHeader", "RunHeaders");
+        write.AddContainer("MMcRunHeader",  "RunHeaders", kFALSE);
+    }
+
+    //
+    // Create and set up the eventloop
+    //
+    MEvtLoop evtloop;
+    evtloop.SetParList(&plist);
+
+    //
+    // Execute your analysis
+    //
+    if (!evtloop.Eventloop())
+    {
+        gLog << err << "ERROR: Star eventloop failed!" << endl;
+        return -1;
+    }
+
+    tlist.PrintStatistics();
+
+    //plist.FindObject("MHSigmaTheta")->Write();
+    //plist.FindObject("MHBlindPixels")->Write();
+
+    gLog << all << "Star finished successfull!" << endl;
+    return 0;
+    */
+}
Index: /tags/Mars_V0-8-4/MagicSoft/Mars/status.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/Mars/status.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/Mars/status.cc	(revision 3781)
@@ -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;
+}
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MFadcDefine.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MFadcDefine.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MFadcDefine.h	(revision 3781)
@@ -0,0 +1,47 @@
+//
+//  --> Frist of all the WIDTH of the time slice of one FADC slice 
+//      this is 3.33333 nsec.
+//
+#define WIDTH_FADC_TIMESLICE   (50./15.)       //  this means 3.33 nsec 
+//
+//  --> Second the number of slices to fill in MFADC. This must by 
+//      connected to the MTrigger class. The time of interest must be
+//      equal in both classes. 
+//
+#define SLICES_MFADC           (TOTAL_TRIGGER_TIME / WIDTH_FADC_TIMESLICE)
+//
+//  --> The amount of FADC slice written to the raw format.
+//
+#define FADC_SLICES  15
+//
+//  --> The amount of ns before trigger that would be read from the ADC
+//      in oder to show also the start of the pulse before the
+//      the trigger time.
+//
+#define TIME_BEFORE_TRIGGER    10.
+//  --> like the trigger the FADC value will also have a standard response
+//      to one single Photo electron. This response is binned with smaller
+//      bins. The WIDTH of that response function is done here. 
+// 
+#define SUBBINS     5.
+#define WIDTH_RESPONSE_MFADC   (WIDTH_FADC_TIMESLICE /  SUBBINS )  
+// 5 sub-bin in one FADC slice 
+//
+//  --> the number of Response slices
+//
+#define RESPONSE_SLICES_MFADC   45         
+//
+//
+#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.
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.cc	(revision 3781)
@@ -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-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcConfigRunHeader.h	(revision 3781)
@@ -0,0 +1,105 @@
+#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 : 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?
+
+    // 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. 
+
+    // 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); }
+
+    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; }
+    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)); }
+
+    ClassDef(MMcConfigRunHeader, 3)  // class for monte carlo configuration information
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.cc
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.cc	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.cc	(revision 3781)
@@ -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-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcCorsikaRunHeader.h	(revision 3781)
@@ -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-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.cxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.cxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.cxx	(revision 3781)
@@ -0,0 +1,301 @@
+#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) {
+
+    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;
+}
+
+
+
+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 ) {
+  //
+  //  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;
+
+}
+
+/*
+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-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.hxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.hxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcEvt.hxx	(revision 3781)
@@ -0,0 +1,214 @@
+#ifndef __MMcEvt__
+#define __MMcEvt__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+class MMcEvt : public MParContainer
+{
+public:
+    //
+    //     ParticleId for Monte Carlo simulation
+    //
+    enum ParticleId_t
+    {
+        kGAMMA  =    1,
+        kPOSITRON =  2,
+        kELECTRON =  3,
+        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] Passed glas
+  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;
+  
+
+
+ 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) ; 
+  
+  ~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) ; 
+
+  //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; }
+
+  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 kPROTON:   return "Proton";
+      case kHELIUM:   return "Helium";
+      case kOXYGEN:   return "Oxygen";
+      case kIRON:     return "Iron";
+      }
+
+      return Form("%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, 3)  //Stores Montecarlo Information of one event (eg. the energy)
+
+};
+
+#endif
+
+
+
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.cxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.cxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.cxx	(revision 3781)
@@ -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-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.hxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.hxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcFadcHeader.hxx	(revision 3781)
@@ -0,0 +1,118 @@
+#ifndef __MMcFadcHeader__
+#define __MMcFadcHeader__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MFadcDefine.h"
+
+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 
+
+ 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];
+    }
+  }
+  
+  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, 4)  //Stores Montecarlo Information describing the FADC behaviour
+
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.cxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.cxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.cxx	(revision 3781)
@@ -0,0 +1,264 @@
+/* ======================================================================== *\
+!
+! *
+! * This file is part of MARS, the MAGIC Analysis and Reconstruction
+! * Software. It is distributed to you in the hope that it can be a useful
+! * and timesaving tool in analysing Data of imaging Cerenkov telescopes.
+! * It is distributed WITHOUT ANY WARRANTY.
+! *
+! * Permission to use, copy, modify and distribute this software and its
+! * documentation for any purpose is hereby granted without fee,
+! * provided that the above copyright notice appear in all copies and
+! * that both that 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).
+// 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, fTelesTheta=90, fTelesPhi = 0 means the telescope is pointing 
+// horizontally towards South. For an explanation, see also TDAS 02-11. 
+//
+////////////////////////////////////////////////////////////////////////////
+
+#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;
+    fTelesTheta = 0.0;
+    fTelesPhi = 0.0;
+    fSourceOffsetTheta = 0.0; 
+    fSourceOffsetPhi = 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  telestheta,
+			const Float_t  telesphi,
+			const Float_t  sofftheta,
+			const Float_t  soffphi,
+			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;
+    fTelesTheta = telestheta;
+    fTelesPhi = telesphi;
+    fSourceOffsetTheta = sofftheta; 
+    fSourceOffsetPhi = soffphi;
+    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-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.hxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.hxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcRunHeader.hxx	(revision 3781)
@@ -0,0 +1,159 @@
+#ifndef MARS_MMcRunHeader
+#define MARS_MMcRunHeader
+///////////////////////////////////////////////////////////////////////
+//                                                                   //
+// MRunHeader                                                        //
+//                                                                   //
+///////////////////////////////////////////////////////////////////////
+
+#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
+  
+  //  Telescope axis position (zenith and azimutal angle)
+  Float_t fTelesTheta;  // >180 (200) means that telescope is always pointing the shower. 
+                        // Otherwise it is Theta where Telescope is pointing.
+  Float_t fTelesPhi;    // See class description. > 360 (400) means that telescope is always pointing the shower.
+                        // Otherwise it is Phi where Telescope is pointing.
+
+  //  Angular distance from the source position to the camera center
+  Float_t fSourceOffsetTheta; 
+  Float_t fSourceOffsetPhi;
+  
+  //  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  telestheta,
+	    const Float_t  telesphi,
+	    const Float_t  sofftheta,
+	    const Float_t  soffphi,
+	    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; }
+  Float_t  GetTelesTheta() const          { return fTelesTheta; }
+  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 GetImpactMax() const            {return fImpactMax;}
+
+  ClassDef(MMcRunHeader, 4)	// storage container for general run info
+};
+#endif
+
+
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.cxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.cxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.cxx	(revision 3781)
@@ -0,0 +1,140 @@
+#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
+  //
+  Int_t i,j;
+
+  cout <<endl << "Monte Carlo Trigger output:" <<endl;
+  cout << " First  Level Trigger in this Event: "<<fNumFirstLevel<<endl; 
+  cout << " Times of first  Level Trigger in this Event: ";
+  for (i=0;i<fNumFirstLevel;i++){
+    cout<< fTimeFirst[i]<<"-";
+  }
+  cout<<endl;
+  cout << " Pixels of first  Level Trigger in this Event : ";
+  for (i=0;i<fNumFirstLevel;i++){
+    for(j=0;j<CAMERA_PIXELS/8+1;j++){
+      cout<<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-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.hxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.hxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrig.hxx	(revision 3781)
@@ -0,0 +1,63 @@
+#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 );  
+  }
+
+  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-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.cxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.cxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.cxx	(revision 3781)
@@ -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-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.hxx
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.hxx	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MMcTrigHeader.hxx	(revision 3781)
@@ -0,0 +1,118 @@
+#ifndef __MMcTrigHeader__
+#define __MMcTrigHeader__
+
+#ifndef MARS_MParContainer
+#include "MParContainer.h"
+#endif
+
+#include "MTriggerDefine.h"
+#include "Mdefine.h"
+
+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
+
+ 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;
+  }
+
+
+
+  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, 3)  //Stores Montecarlo Information which describes the used trigger
+
+};
+
+#endif
+
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MTriggerDefine.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MTriggerDefine.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/MTriggerDefine.h	(revision 3781)
@@ -0,0 +1,105 @@
+//
+//
+//      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 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*SLICES_PER_NSEC) 
+//
+//
+//
+//
+//       ------>>>   SETTINGS for the RESPONSE FUNCTION
+// 
+#define RESPONSE_SLICES        40
+//
+//       This is for the standard response Signal to 1 Photoelectron
+//       that leaves the Photocathode
+//       The whole Timescale for the signal is 10 nsec
+//
+//       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 phote electron ) 
+//
+//
+//       -------->>> 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-8-4/MagicSoft/include-Classes/MMcFormat/Makefile
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/Makefile	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/Makefile	(revision 3781)
@@ -0,0 +1,58 @@
+##################################################################
+#
+#   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
+
+# @endcode 
+
+INCLUDES = -I.  -I../mbase -I../MBase -I../mgeom
+
+# @code 
+
+CINT     = Mc
+LIB      = mmc.a
+
+#------------------------------------------------------------------------------
+
+.SUFFIXES: .c .cc .cxx .h .hxx .o 
+
+SRCFILES = MMcTrigHeader.cxx \
+	   MMcFadcHeader.cxx \
+	   MMcRunHeader.cxx \
+	   MMcEvt.cxx \
+           MMcTrig.cxx 
+
+SRCFILESCC = MMcConfigRunHeader.cc \
+	     MMcCorsikaRunHeader.cc
+
+
+SRCS    = $(SRCFILES) 
+
+HEADERS = $(SRCFILES:.cxx=.hxx) $(SRCFILESCC:.cc=.h)
+OBJS    = $(SRCFILES:.cxx=.o) $(SRCFILESCC:.cc=.o)
+
+############################################################
+
+all: $(LIB)
+
+include ../Makefile.rules 
+
+#clean:	rmcint rmobjs rmcore rmlib
+
+mrproper:	clean rmbak
+
+# @endcode
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McIncl.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McIncl.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McIncl.h	(revision 3781)
@@ -0,0 +1,3 @@
+#ifndef __CINT__
+
+#endif // __CINT__
Index: /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McLinkDef.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McLinkDef.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/McLinkDef.h	(revision 3781)
@@ -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 MMcEvt+;
+#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-8-4/MagicSoft/include-Classes/MMcFormat/Mdefine.h
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/Mdefine.h	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/Mdefine.h	(revision 3781)
@@ -0,0 +1,42 @@
+//
+//     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. 
+
+#define     FADC_SLICES            15
+
+//     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
+
+#define MAX_ADC 30  // nummber of ADC conversions per pixel
+
+//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-8-4/MagicSoft/include-Classes/MMcFormat/readme.txt
===================================================================
--- /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/readme.txt	(revision 3781)
+++ /tags/Mars_V0-8-4/MagicSoft/include-Classes/MMcFormat/readme.txt	(revision 3781)
@@ -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!
+ 
